我有以下 View ,它创建 10 个 ajax.beginform ,,但我面临的问题是,如果在创建对象期间发生错误,则 ModelState.AddModelError 将不会显示在 View 上,尽管我已经设置了 @Html.ValidationSummary(true)
View 如下所示
@model Medical.Models.VisitLabResult
@for (int item = 0; item < 10; item++)
{
<tr id = @item>
@using (Ajax.BeginForm("CreateAll", "VisitLabResult", new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = item.ToString() + "td",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "progress2",
OnSuccess = string.Format(
"disableform({0})",
Json.Encode(item)),
}))
{
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()
<td>
@Html.DropDownList("LabTestID", String.Empty)
@Html.ValidationMessageFor(model => model.LabTestID)
</td>
<td>
@Html.EditorFor(model => model.Result)
@Html.ValidationMessageFor(model => model.Result)
</td>
<td>
@Html.EditorFor(model => model.DateTaken)
@Html.ValidationMessageFor(model => model.DateTaken)
</td>
<td>
@Html.EditorFor(model => model.Comment)
@Html.ValidationMessageFor(model => model.Comment)
</td>
<td>
<input type="submit" value="Create" />
</td>
<td id = @(item.ToString() + "td")>
</td>
}
</tr>
}
</table>
我定义 ModelState.AddModelError 的操作方法如下所示:-
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateAll(VisitLabResult vlr, int visitid = 28)
{
try
{
if (ModelState.IsValid)
{
var v = repository.GetVisit(visitid);
if (!(v.EligableToStart(User.Identity.Name))){
return View("NotFound");
}
vlr.VisitID = visitid;
repository.AddVisitLabResult(vlr);
repository.Save();
return Content("Addedd Succsfully");
}
}
catch (DbUpdateException)
{
JsonRequestBehavior.AllowGet);
ModelState.AddModelError(string.Empty, "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");
}
}
那么我如何在我的 View 上显示 ModelState.AddModelError。
最佳答案
我强烈建议您更改 try{ } catch(){ }
首先检查给定 ID 是否存在访问 如果是这样,只需返回带有添加的模型错误的模型
if (visitExists)
{
ModelState.AddModelError("CustomError", "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");
return View(vlr);
}
//Other code here
将 AddModelError 更改为
ModelState.AddModelError("CustomError", "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");
在您看来,只需添加一个
@Html.ValidationMessage("CustomError")
然后,当您返回模型时,错误将显示在您放置 @Html.ValidationMessage ...的位置
关于asp.net-mvc-3 - ModelState.AddModelError 未显示在我的 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10406998/