我想要做软垫验证,并返回假和显示消息,如果验证失败。
在控制器中,下面的代码用于向数据库提交已发布的数据。
[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);
}下面是视图文件中的代码(cshtml)
@Html.ValidationMessage("MessageError")
.....
$.AJAX call to `SubmitDa` controller's method.消息没有出现在"MessageError“验证消息中。请告诉我这里出了什么问题。
谢谢
发布于 2014-02-11 11:07:16
如果您想要使用模型状态来处理错误,就不应该真正发送JSON响应。尽管如此,您可以通过让控制器只在成功的情况下返回JSON来处理它,并且页面处理响应的方式不同
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!
}在页面上,如下所示:
<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>https://stackoverflow.com/questions/21699193
复制相似问题