Question

I want to do cusotm validation and return false and show message in case of validation fail.

In controller below code is used to submit posted data to database.

       [HttpPost]
       public JsonResult SubmitDa(IList<AdViewModel> s, String section)
           {

            ...........
              ..........


            ModelState.AddModelError("MessageError", "Please enter AttendanceDate");

             JSONSubmit r = new JSONSubmit();
            r.ErrorCount = iError;
            r.errors = errors;

           return Json(r, JsonRequestBehavior.AllowGet);

       }

Below is the code in view file (cshtml)

       @Html.ValidationMessage("MessageError")  
        .....  

       $.AJAX call to `SubmitDa` controller's method.

Message is not appearing at "MessageError" validation message. please suggest me what is wrong here.

Thanks

Was it helpful?

Solution

If you want to use the modelstate for errors you shouldn't really be sending a JSON response. Having said that you can handle it by having the controller return JSON only in the case of success, and the page handles the response differently

IE:

[HttpPost]
public ActionResult SubmitDa(IList<AdViewModel> s, String section)
{

        ...........
          ..........


        ModelState.AddModelError("MessageError", "Please enter AttendanceDate");

         JSONSubmit r = new JSONSubmit();
        r.ErrorCount = iError;
        r.errors = errors;
       if (r.ErrorCount != 0)
           return Json(r, JsonRequestBehavior.AllowGet);

       return View("ViewName", s); // <-- just return the model again to the view,
                                   //     complete with modelstate!
}

on the page something like:

<script>

$("#buttonId").click({
   $.ajax({
     type: "POST",
     url: "PostBackURL",
     data: $("#formID").serialize(),
     success: function (response){
       //test for a property in the JSON response
       if(response.ErrorCount && response.ErrorCount == 0) 
       {
           //success! do whatever else you want with the response

       } else {
          //fail - replace the HTML with the returned response HTML.
          var newDoc = document.open("text/html", "replace");
          newDoc.write(response);
          newDoc.close();
       }

     }
   });
});

</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top