Jquery – How to access the model errors on the client side

asp.net-mvc-3jquery

I don't like the built in Html.ValidationSummary helper because I want a single message displayed at the top of my form such as…

There are validation errors. The invalid fields have been highlighted.

The built in ValidationSummary either doesn't output anything at all or outputs a list of all the fields. I just want a succinct message.

I have a div at the top of my form styled the way I want it and then when the page loads I hook the following method onto the form…

function CheckFormForValidationErrors() 
{
    if (!$("form").valid()) 
    {
        $(".validation-notification").css("visibility", "visible");
    }
}

This works great when there are validation errors on the client. The problem is when the client side validation succeeds but the server side validation such as a login form. If the user enters a proper username and password the form validation succeeds but the login fails. On the server side I am adding a model error like so…

ModelState.AddModelError(string.Empty, "Login failed");

But I can't figure out how to get the message to display on the client. If you have a better idea to accomplish my goal then I'm willing to scrap my idea and change course. What I'm trying to do shouldn't be that hard.

Best Answer

When you're in your view, the ModelState is located in the ViewData

 ViewData.ModelState

And to get the error messages:

 foreach(string key in ViewData.ModelState.Keys)
 {
     foreach (var error in ViewData.ModelState[key].Errors)
     {
         string err = error.ErrorMessage;
     }
 }

and in Razor, maybe this will work (my Razor is rusty)

@if (!ViewData.ModelState.IsValid)
{
    <ul>
    @foreach (string key in ViewData.ModelState.Keys)
    {
        @foreach (var error in ViewData.ModelState[key].Errors)
        {
            <li>@error.ErrorMessage</li>
        }
    }
    </ul>
}