我想做cusotm验证并在验证失败时返回false和show message。
在控制器下面,代码用于将发布的数据提交到数据库。
[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”验证消息中。请告诉我这里有什么问题。
由于
答案 0 :(得分:2)
如果您想使用modelstate进行错误,则不应该发送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>