Tôi có một trang tạo sử dụng hành động JsonResult thay vì ActionResult. Trong hành động ActionResult, các lỗi được hiển thị trên khung nhìn bên cạnh trường vi phạm. Ngay bây giờ JsonResult chỉ trả về một chuỗi được hiển thị trong một hộp cảnh báo.Hiển thị lỗi ModelState được trả về bởi JsonResult trong dự án MVC 3?
Tôi có thể hiển thị lỗi ModelState trên chế độ xem không?
Bộ điều khiển
[HttpPost]
public JsonResult Create(Tload tload)
{
if (ModelState.IsValid)
{
...save changes
return Json(new { Success = 1, TransloadID = transload.TransloadID, ex = "" });
}
else
{
string totalError = "";
foreach (var obj in ModelState.Values)
{
foreach (var error in obj.Errors)
{
if (!string.IsNullOrEmpty(error.ErrorMessage))
{
totalError = totalError + error.ErrorMessage + Environment.NewLine;
}
}
}
return Json(new { Success = 0, ex = new Exception(totalError).Message.ToString()});
}
jquery/mã javascript trong quan điểm
function Save() {
// Step 1: Read View Data and Create JSON Object
...do stuff here
// Set 2: Ajax Post
// Here i have used ajax post for saving/updating information
$.ajax({
url: '/Expedite/Create',
data: JSON.stringify(salesmain),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
if (result.Success == "1") {
window.location.href = "/Expedite/index";
}
else {
alert(result.ex);
}
}
});
}