Custom ValidationSummary template Asp.net MVC 3

Dynamikus picture Dynamikus · May 2, 2011 · Viewed 51.2k times · Source

I am working on a project with Asp.Net MVC3

In a View I have @Html.ValidationSummary(true) and as usually it produces

<div class="validation-summary-errors">
    <ul>
        <li>Something bad Happened!</li>
    </ul>
</div>

How can I extend this ValidationSummary to MyValidationSummary and produces the Html Code template something like this:

<div class="notification warning"> 
    <span></span> 
    <div class="text"> <p>Something bad Happened!</p> </div> 
</div>

Answer

flo scheiwiller picture flo scheiwiller · Dec 16, 2011

My approach is to use a custom ValidationSummary.cshtml:

@model ModelStateDictionary

@if(!Model.IsValid)
{
    <div class="validation-summary-errors">
        <ul>
            @foreach (var modelError in 
                     Model.SelectMany(keyValuePair => keyValuePair.Value.Errors))
            {
                <li>@modelError.ErrorMessage</li>
            }
        </ul>
    </div>
}

Put this partial view in your Shared folder and refer to it from your code:

@Html.Partial("_ValidationSummary", ViewData.ModelState);

This way you remain in full control of your html.