Question

I have a ajax form in my view

@using (Ajax.BeginForm("AttendeeAvailability", "Response", new AjaxOptions { HttpMethod = "POST", OnSuccess = "done" }))
{
    @Html.ValidationSummary(true)
    ....
    //some stuff
    ....
}
<script type="text/javascript">

    function done() {
     //do something;
    }
</script>

Here is the post method of controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AttendeeAvailability(AttendeeAvailableDateTime response)
{            
    ....
    ....
    if (somecheck1)
    {
        ModelState.AddModelError(string.Empty,"Check error1");
        return View();
    }
    if (doesTimeExists2)
    {
        ModelState.AddModelError(string.Empty,"Check error2");
        return View();
    }
    //do some database actions
    return View();
}

Currently I'm not getting any Modelstate's error message that is being set in controller.

I'm guessing because it calls the done function that I have in view when tasks in controller are completed successfully.

How can I send some errors and display them as Modelstate error in this case?

Was it helpful?

Solution

Change the form call header (add a parameter to the done function):

@using (Ajax.BeginForm("AttendeeAvailability", "Response", 
     new AjaxOptions { HttpMethod = "POST", OnSuccess = "done(data)" }))

...and the JavaScript:

<script type="text/javascript">
    function done(data) {
    //do something with the data
    }
</script>

How your data looks depends entirely on how you structure it in your action:

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult AttendeeAvailability(AttendeeAvailableDateTime response)
{            
   ....
   ....
   if (somecheck1)
   {
        //ModelState.AddModelError(string.Empty,"Check error1");
        return Json(new { error = "Check error1" }, JsonRequestBehavior.AllowGet);
   }
   if (doesTimeExists2)
   {
       //ModelState.AddModelError(string.Empty,"Check error2");
       return Json(new { error = "Check error2" }, JsonRequestBehavior.AllowGet);
   }

   //do some database actions
   return Json(new { success = "Success" }, JsonRequestBehavior.AllowGet);
}

Following this, you can access the data by parsing it:

<script type="text/javascript">
    function done(data) {
        var confirmation = data;
        if (confirmation["success"] != undefined) {
           alert(confirmation["success"]);
        }
        else if (confirmation["error"] != undefined) {
           alert(confirmation["error"]);
        }
    }
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top