asp.net mvc內建的資料驗證功能為我們提供了一個非常方便的資料驗證體驗,但是如果我們通過Ajax方式訪問我們的Action並且返回驗證的錯誤提示就比較麻煩了,經過反覆實驗終於找了一個解決方案,特此記錄下來以備忘。
Action代碼
代碼
1 [HttpPost]
2 public ActionResult CreateComment(Comment comment)
3 {
4 if (!ModelState.IsValid)
5 {
6 List<string> sb = new List<string>();
7 //擷取所有錯誤的Key
8 List<string> Keys = ModelState.Keys.ToList();
9 //擷取每一個key對應的ModelStateDictionary
10 foreach (var key in Keys)
11 {
12 var errors = ModelState[key].Errors.ToList();
13 //將錯誤描述添加到sb中
14 foreach (var error in errors)
15 {
16 sb.Add(error.ErrorMessage);
17 }
18 }
19 return Json(sb);
20 }
21 else
22 {
23 return Json(commentRepository.InsertComment(comment));
24 }
25 }
JavaScript代碼
代碼
$("#commentform").submit(function () {
$.ajax({
type: "POST",
url: "/AjaxResult/CreateComment/",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
if (data == true) {
alert("成功");
ShowPage(articleID, pageSize, 1);
}
else if (data != true && data != false) {
var result = "";
for (var i in data) {
result = result + data[i] + "\r\n";
}
alert(result);
}
},
global: false
});
return false;
});
具體的就不解釋了,自己能看懂就行了。