Wednesday, April 3, 2013

Page validation in MVC3 with AJAX

There are situations where we can not submit the page and need to show server side validation in page. For example, we are saving a detail page using AJAX and need to show validation errors in page. This will need some extra amount of work, but in the end, it is quite simple.
Lets say we have a field Phone Number in detail page, that is integer. First step is a normal one, that is to create a text box and hidden error mesage field like below:

@Html.TextBoxFor(m => m.PhoneNumber, new {@Value = Model.PhoneNumber}) @Html.ValidationMessage("PhoneNumber",  new { @id = "errorMessagePhoneNumber", @class = "errorMessage" })

Now, when a button is pressed, we do a ajax call to controller.
In this action, we can add extra validation error to ModelState like
   ModelState.AddModelError("name of some input", "some message")
Even if the ModelState.Isvalid is true, once we add error mesage to ModelState, Its IsValid state will be set to false.

Adding extra error message as mentioned above is optional depending on your need.

Lets focus on returning ModelState error to the view that called this controller via ajax.

If ModelState.IsValid is false, We need to build the json string out of this and return to view, since modelstate errors can not be returned, (or atleast, that is what i faced problem).
For this, lets create a function like this
public List<ErrorList> ErrorDetails(ModelStateDictionary obj), that accepts ModelStateDictionary as parameter
Then we need to loop through obj and put it in List<ErrorList> object.
like below:

     ErrorList error = new ErrorList();
     error.Key = item.Key;
     error.Value = item.Value.Errors[0].ErrorMessage;
     errorsList.Add(error);

 Then we return errorsList from this function. We call this fucntion from controller like below

 SomeClass Errors = new SomeClass ();
 List<ErrorList> ErrorList = Errors.ErrorDetails(this.ModelState);
 return Json(new { Isvalid = ModelState.IsValid, Errors = ErrorList});

 Now the view will get this json string that has ModelState.IsValid and errorList in Errors. So we can now iterate through Erros (in on sucess call back of ajax), and respective errors are shown in respective input fields with following code:

 $.each(result.Errors, function (key, value) {
        $("#errorMessage" + value.Key).html(value.Value);
 });
 
  Here the value.Key will have input name so $("#errorMessage" + value.Key) will be the corresponding error message field for that element. and it puts the error message in it from value.Value.

No comments:

Post a Comment