Ajax.BeginForm添加从控制器发送的ModelSstate错误?

时间:2014-03-25 14:35:44

标签: jquery ajax asp.net-mvc asp.net-ajax

我的视图中有一个ajax表单

@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>

这是控制器的post方法

[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();
}

目前我没有收到任何在控制器中设置的Modelstate错误消息。

我猜是因为当控制器中的任务成功完成时,它会调用我在视图中的完成功能。

在这种情况下,如何发送一些错误并将其显示为Modelstate错误?

1 个答案:

答案 0 :(得分:2)

更改表单调用标题(将参数添加到done函数):

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

...和JavaScript:

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

data的外观完全取决于您在行动中如何构建它:

[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);
}

在此之后,您可以通过解析来访问数据:

<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>