我想在ajax提交返回錯誤後出現錯誤。我不確定我錯過了什麼,但我無法讓它工作。這個問題基本上是一樣的 - ModelState.AddModelError is not being displayed inside my view但我仍然沒有任何運氣。我對Ajax和MVC(任何版本)的使用經驗仍然有限。這是一個非常簡單的例子,其中大部分是我從前面的鏈接中獲得的。MVC 4 Ajax.BeginForm和ModelState.AddModelError
查看:test.cshtml
@model TestProject.VisitLabResult
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
@Scripts.Render("~/Scripts/ckeditor/ckeditor.js")
@{
AjaxOptions ajaxOpts = new AjaxOptions
{
Url = Url.Action("test"),
HttpMethod = "Post",
LoadingElementId = "loading",
LoadingElementDuration = 500,
OnSuccess = "processData"
};
}
@Html.ValidationMessage("CustomError")
<div id="loading" class="load" style="display:none">
<p>Saving...</p>
</div>
<table>
@for (int item = 0; item < 10; item++)
{
<tr id = @item>
@using (Ajax.BeginForm(ajaxOpts))
{
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()
<td>
<input type="submit" value="Create" />
</td>
<td id = @(item.ToString() + "td")>
</td>
}
</tr>
}
</table>
控制器:HomeController.cs
public ActionResult test()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult test(VisitLabResult vlr, int visitid = 28)
{
try
{
if (ModelState.IsValid)
{
if (Request.IsAjaxRequest())
{
throw new Exception("error");
}
else
return View(vlr);
}
else
return View(vlr);
}
catch (Exception ex)
{
ModelState.AddModelError("CustomError", "The Same test Type might have been already created, go back to the Visit page to see the available Lab Tests");
return View(vlr);
}
}
型號
public class VisitLabResult
{
public int visitid { get; set; }
}
如果一個Ajax請求我拋出一個錯誤,它的捕獲和一個錯誤被添加到ModelState中。儘管這個錯誤從未出現在頁面上。我是否以正確的方式接近這一切?或者我需要採取不同的路線?我感謝任何幫助。
發現這個(http://stackoverflow.com/a/7329127/978528)更多的搜索後,似乎做我所需要的。 – nickfinity