jQuery Validate, ASP.NET MVC ModelState Errors (Async POST)

Felipe Oriani picture Felipe Oriani · Sep 2, 2011 · Viewed 24k times · Source

I'm developing a web app with asp.net mvc 3 and I have some form that POST to an async action (via ajax). This action recives a ViewModel with some data annotations to validate it. The validation works fine but when the validators return a error I don't know how can I return it to show in my view (because the POST was made by ajax).

My action is something like:

[HttpPost]
public ActionResult SaveCustomer(CustomerViewModel input) {
    if (!ModelState.IsValid) { // <-- business validation
        return Json(new { success = false, errors = ???});
    }
    // persist 
    return Json(new { success = true });
}

How can I show this errors with jquery validate in my view? If it's possible to post some code to sample... I would appretiate that!

Thanks guys!

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 2, 2011

Instead of sending JSON in case of error I would put the form inside a partial and then have the controller action return this partial in case of error. The problem with JSON is that you could in fact fetch the errors from the ModelState using LINQ, but it could be a PITA to show them on the view.

So:

<div id="myform">
    @Html.Partial("_MyForm")
</div>

and then inside _MyForm.cshtml:

@model CustomerViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
    <br />
    @Html.EditorFor(x => x.Bar)
    @Html.ValidationMessageFor(x => x.Bar)
    <br />
    <input type="submit" value="OK" />
}

and the controller action would become:

[HttpPost]
public ActionResult SaveCustomer(CustomerViewModel model)
{
    if (!ModelState.IsValid)
    {
        return PartialView("_MyForm", model);
    }
    return Json(new { success = true });
}

and the last step is to AJAXify this form which could be done in a separate javascript file:

$(function () {
    $('#myform').delegate('form', 'submit', function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) { 
                    // We have a JSON object in case of success
                    alert('success');
                } else {
                    // We have the partial with errors in case of failure
                    // so all we have to do is update the DOM
                    $('#myform').html(result);
                }
            }
        });
        return false;
    });
});