One solution is to implement your own extension method on HtmlHelper that does something different to the default ValidationMessageFor behavior. The sample @Html.ValidationMessagesFor method below will concatenate multiple error messages that have been added to the ModelState during server-side validation (only).
public static MvcHtmlString ValidationMessagesFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
{
var propertyName = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).PropertyName;
var modelState = htmlHelper.ViewData.ModelState;
// If we have multiple (server-side) validation errors, collect and present them.
if (modelState.ContainsKey(propertyName) && modelState[propertyName].Errors.Count > 1)
{
var msgs = new StringBuilder();
foreach (ModelError error in modelState[propertyName].Errors)
{
msgs.AppendLine(error.ErrorMessage);
}
// Return standard ValidationMessageFor, overriding the message with our concatenated list of messages.
return htmlHelper.ValidationMessageFor(expression, msgs.ToString(), htmlAttributes as IDictionary<string, object> ?? htmlAttributes);
}
// Revert to default behaviour.
return htmlHelper.ValidationMessageFor(expression, null, htmlAttributes as IDictionary<string, object> ?? htmlAttributes);
}
This is useful if you have custom business validation you're applying across a collection belonging to your model (for example, cross-checking totals), or checking the model as a whole.
An example using this, where a collection of Order.LineItems are validated server-side:
@using MyHtmlHelperExtensions // namespace containing ValidationMessagesFor
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.LineItems)
<ul>
@Html.EditorFor(m => m.LineItems)
</ul>
@Html.ValidationMessagesFor(m => m.LineItems)
}
tag in between for instance – theB3RV Apr 19 '16 at 20:18