[RESOLVED]Show errors from Json response against fields after ajax request.

I have an Ajax post:

{ url: '@Url.Action("SaveName", "JSON")', type: 'POST', cache: false, async: false, contentType: 'application/json; charset=utf-8', dataType: 'json', data: JSON.stringify($('#modalForm').serializeObject()) }) .success(function (response) { alert(response); }) .error(function (response) { alert(response); })

Which when validated server side and !ModelState.isValid() returns a serialized modelstate as follows: (In this example LastName is in error)

{"FirstName":{"Value":{"AttemptedValue":"test","Culture":"en-GB","RawValue":"test"},"Errors":[]},"LastName":{"Value":{"AttemptedValue":"Jones","Culture":"en-GB","RawValue":"Jones"},"Errors":[{"Exception":null,"ErrorMessage":"Fluent - Last Name of Jones is not allowed"}]},"CreditCard":{"Value":{"AttemptedValue":"","Culture":"en-GB","RawValue":""},"Errors":[]}}

My view fields are set up as follows:

@Html.LabelFor(m => m.LastName)
@Html.TextBoxFor(m => m.LastName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.LastName)

How do I bind the error back to the Validation Message on the response?

Try changing your error function  to below.

 error: function (x, y, z) {
                    alert(x.responseText + 'n' + y + 'n' + z);

If you are getting a non-error response, then you will need to get the appropriate property in your success function by referencing the JSON object property appropriately. In your success function you can treat your response as an object and simply access
its properties and then set the validation message div or span inner html property to the ErrorMessage property of the first Error in the Errors collection for that input item ( like for lastname or firstname or creditcard).

success( response)
  var errors = response.LastName.Errors;
  var errorMessage = errors[0].ErrorMessage;//get a nested object property
$('#lastNameError').html( errorMessage ); }

The response is set to return a status 400 however this can be disabled and return a 200 status. I can display the response as you’ve suggested, however, I want to display the message bound to the input that it relates to. In the way that the Unobtrusive
errors do.

Last Name
Error Message here 

I am not sure if you can have the same server-side validation out-of-the-box that is there  in ASP.Net WebForm where the error message gets automatically bound to a validation control in the web page. 

I think you will need to use some client-side framework like knockout or kendoui or backbone or use some specialized jQuery like below inside your success function.

 $.each(response,function(key,value) {
          var errors =  value.Errors;
          if(errors.length > 0) {
          var errorMessage = errors[0].ErrorMessage;


<%= Html.ValidationMessage("LastName", "*") %>

I think if you use Html helper as above, it will automatically bind to any validation errors for the model you are using for the view.
May be this is what you need for automatic binding. This code should go into your  View.

This line of code should go just after the LastName textbox where you want the error message to appear.

You can add similar elements for each of your model input fields displayed in your MVC view.

Also, I am assuming you are using Data Annotations like below in your Model, or if not, then you are adding model state errors.

Data Annotation (this code goes into your Model code)

public string LastName { get; set; }

Model Error ( this code goes into your action method)

if (person.LastName.Trim().Length == 0)
     ModelState.AddModelError("Last Name", "Last Name is required.");

Leave a Reply