ModelState错误未在视图中显示

时间:2012-02-09 14:27:13

标签: c# asp.net-mvc-3

我有一个动作通过调用我的BLL实体的Save方法来保存记录。实体负责自己的内部验证,如果需要字段但验证失败,因为用户没有输入值,则实体会抛出错误。我在我的操作中捕获了该错误并返回相同的视图。问题是我的ValidationSummary中没有显示错误。

是的我意识到我已经通过attibute与MVC进行了模型验证,但是这个实体在其他地方使用,如果UI不能/不能这样做,必须进行冗余验证,例如在批处理服务作业中使用。

这是我的行动:

public ActionResult Edit(EntityModel model) {
    if (ModelState.IsValid) {
        var entity = new Entity(model.ID, model.Name, model.IsActive);
        try {
            entity.Save(User.Identity.Name);
            return RedirectToAction("List");
        }
        catch (Exception ex) {
            ModelState.AddModelError("", ex.Message);
        }
    }
    return View(model);
}

这是我的观点:

@model ELM.Select.Web.Models.EntityModel

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>DefermentTypeViewModel</legend>

        @Html.HiddenFor(model => model.ID)

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.IsActive)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.IsActive)
            @Html.ValidationMessageFor(model => model.IsActive)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

为什么我添加到modelstate的错误不会显示在我的验证中?

1 个答案:

答案 0 :(得分:21)

更改您的查看代码:

@Html.ValidationSummary(true)

为:

@Html.ValidationSummary(false)

根据the MSDN Reference on ValidationSummary(),这是方法定义:

public static MvcHtmlString ValidationSummary(
    this HtmlHelper htmlHelper,
    bool excludePropertyErrors
)

请注意bool参数,如果将其设置为true(就像您最初那样),则会排除属性错误。将其更改为false,这样可以获得您想要的效果。