Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <em>server-side</em> validation (only).</p> <pre><code>public static MvcHtmlString ValidationMessagesFor&lt;TModel, TProperty&gt;(this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; 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) &amp;&amp; modelState[propertyName].Errors.Count &gt; 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&lt;string, object&gt; ?? htmlAttributes); } // Revert to default behaviour. return htmlHelper.ValidationMessageFor(expression, null, htmlAttributes as IDictionary&lt;string, object&gt; ?? htmlAttributes); } </code></pre> <p>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.</p> <p>An example using this, where a collection of Order.LineItems are validated server-side:</p> <pre><code>@using MyHtmlHelperExtensions // namespace containing ValidationMessagesFor @using (Html.BeginForm()) { @Html.LabelFor(m =&gt; m.LineItems) &lt;ul&gt; @Html.EditorFor(m =&gt; m.LineItems) &lt;/ul&gt; @Html.ValidationMessagesFor(m =&gt; m.LineItems) } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload