Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 490
Felipe Oriani Avatar asked Sep 02 '11 17:09

Felipe Oriani


People also ask

How do I know if my ModelState is valid?

Below the Form, the ModelState. IsValid property is checked and if the Model is valid, then the value if the ViewBag object is displayed using Razor syntax in ASP.Net MVC.

How do I display ModelState errors?

AddModelError() method. The ValidationSummary() method will automatically display all the error messages added into the ModelState .

Why is my ModelState IsValid false?

IsValid is false now. That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.


1 Answers

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;     }); }); 
like image 198
Darin Dimitrov Avatar answered Sep 27 '22 22:09

Darin Dimitrov