我有以下视图,它创建了10个ajax.beginform,但我遇到的问题是在创建对象期间发生错误,然后模型中不会显示ModelState.AddModelError我设置了@Html.ValidationSummary(true)
该视图如下所示
@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的action方法如下所示: -
[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");
}
}
所以我如何在我的视图中显示ModelState.AddModelError。
答案 0 :(得分:65)
我会劝你改变你的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 ...
的位置答案 1 :(得分:8)
@Html.ValidationSummary(true)
仅显示有关模型属性的错误消息,如果您还要显示添加的消息,则添加
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.ValidationSummary(false)
如果您需要在输入字段附近显示验证消息,则需要设置@Html.ValidationSummary(true)
并按照Syneryx建议的步骤进行操作
答案 2 :(得分:5)
您可以在视图中使用ViewData
词典访问ModelState
数据。
例如:
在行动中:
ModelState.AddModelError("CustomError", "Error 1");
ModelState.AddModelError("CustomError", "Error 2");
并获取“错误1”消息:
ViewData.ModelState["CustomError"].Errors[0].ErrorMessage