Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The following example works for me when using unobtrusive JavaScript in MVC3. I'm doing something very similar. Given the following <code>JsonResponse</code> class:</p> <pre><code>public enum Status { Ok, Error } public class JsonResponse { public Status Status { get; set; } public string Message { get; set; } public List&lt;string&gt; Errors { get; set; } } </code></pre> <p>My controller can have a method thus:</p> <pre><code>[HttpPost] public ActionResult Login(UserLoginModel model) { JsonResponse res = new JsonResponse(); if (!ModelState.IsValid) { res.Status = Status.Error; res.Errors = GetModelStateErrorsAsString(this.ModelState); res.Message = "Oh dear, what have you done. Check the list of errors dude!"; } else { // Save it here... // Return success res.Status = Status.Ok; res.Message = "Everything was hunky dory"; } return Json(res); } </code></pre> <p>And the ModelStateDictionary can be enumerated for the errors as so:</p> <pre><code>private List&lt;string&gt; GetModelStateErrorsAsString(ModelStateDictionary state) { List&lt;string&gt; errors = new List&lt;string&gt;(); foreach (var key in ModelState.Keys) { var error = ModelState[key].Errors.FirstOrDefault(); if (error != null) { errors.Add(error.ErrorMessage); } } return errors; } </code></pre> <p>Then in my view I can have the following JSON POST:</p> <pre><code>&lt;script type="text/javascript"&gt; $("form").submit(function (evt) { // validate $('form').valid(); // extract values to submit var form = $(this), username = form.find("[name=Username]").val(), password = form.find("[name=Password]").val(), json = JSON.stringify({ Username: username, Password: password }); $.ajax({ url: form.attr("action"), type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', data: json, success: function (result) { alert(result.Message); } }); // stop form submitting evt.preventDefault(); }); &lt;/script&gt; </code></pre> <p>I'm using <code>jQuery.tmpl</code> to display the errors. I have excluded that from this example though.</p>
 

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