1
votes

I m making jquery ajax post on a button click and doing unobtrusive form validation as below

 $.validator.unobtrusive.parse('#formSite');
 $('#formSite').validate();
 if ($('#formSite').valid()) {

   $.ajax({
        type: "POST",
        url: "/Controller/ActionMethod",
        cache: false,
        content: "application/html; charset=utf-8",
        data: {
            //data
        },
        success: function (data) {
                 if(data.success)
                 {
                 //processing
                 }else
                 {
                    //show errors
                 }
     }

The above works perfectly fine for any existing model errors. In my controller I manually add errors in the modelstate and need to parse the form again showing those errors. How can we call $.validator.unobtrusive.parse('#formSite') with the additional server side errors and display them. My controller action method looks like this.

if (condition)
  {
    ModelState.AddModelError("PostCode", "Postcode District is invalid");
  }
    //processing
var modelErrors = AllErrors(ModelState);
return Json(new { success = false, modelErrors },JsonRequestBehavior.AllowGet);
1
You gonna display validation summary or just a single custom validation message?? - Guruprasad J Rao
What is the actual point of this. If you want to return the view with errors, do a normal submit. And $.validator.unobtrusive.parse('#formSite'); does not do anything unless you first set the validator to null anyway - user3559349
@GuruprasadRao I need to show validation summary. - rumi
@Stephen Muecke The way the application is designed I need to use Ajax post, can't do the normal submit and all i m trying to do is to get the errors from the server and display them using jquery unobtrusive validator. - rumi
You cant display them using the validator unless you return the view, replace the form, reset the validator and reparse it (validation works on controls in a form, not on json data). If you want to display a message, then add an <div> and update its contents with the error message. - user3559349

1 Answers

1
votes