asp.net-mvc-3 – ModelState.AddModelError不显示在我的视图

我有以下视图,其中创建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。

解决方法

我会敦促你改变你的try {} catch(){}

并首先检查是否存在给定id的访问
并且如果这样简单地返回具有添加的模型误差的模型

if (visitExists)
    {
         ModelState.AddModelError("CustomError",go back to the Visit page to see the avilalbe Lab Tests");
         return View(vlr);    
    }
    //Other code here

将您的AddModelError更改为

ModelState.AddModelError("CustomError",go back to the Visit page to see the avilalbe Lab Tests");

在你看来简单地添加一个

@Html.ValidationMessage("CustomError")

然后当你返回你的模型时,错误显示你放置了@ Html.ValidationMessage …

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....