ModelState.AddModelError - 未显示错误

时间:2013-03-19 15:57:38

标签: asp.net-mvc asp.net-mvc-3 modelstate

我想在控制器中捕获到异常后为电子邮件字段设置错误消息:

...
catch (EmailAlreadyExistsException emailAlreadyExistsException)
{
    ModelState.AddModelError("Useraccount_Email", "This is an error message");

    RegisterViewModel viewModel = new RegisterViewModel
    {
        Useraccount = useraccount,
        InformationMessages = InformationMessageHelper.GetInformationMessages()
    };
    return PartialView(viewModel);
}
...

现在应该在我的视图中显示错误消息:

@using (Ajax.BeginForm("Register", new AjaxOptions { HttpMethod = "Post", OnSuccess = "registerAjaxSuccess" }))
{
    @Html.ValidationSummary(true)        
    <div class="ym-grid">
        <div class="ym-g33 ym-gl">
            <div class="ym-gbox">
                @Html.LabelFor(model => model.Useraccount.LastName)
            </div>
...
    <div class="ym-grid">
        <div class="ym-g33 ym-gl">
            <div class="ym-gbox">
                @Html.LabelFor(model => model.Useraccount.Email)
            </div>
        </div>
        <div class="ym-g33 ym-gl">
            <div class="ym-gbox">                  
                @Html.EditorFor(model => model.Useraccount.Email, new { required = "required" })                 
            </div>
        </div>
        <div class="ym-g33 ym-gr">
            <div class="ym-gbox">
               @Html.ValidationMessageFor(model => model.Useraccount.Email)
            </div>
        </div>
    </div>
...

但在这种情况下没有显示任何内容。 :( 我做错了什么?

2 个答案:

答案 0 :(得分:8)

添加模型错误时,处理复杂对象时的正确分隔符是点.,而不是unserscore _

因此以下调用应该有效:

ModelState.AddModelError("Useraccount.Email", "This is an error message");

答案 1 :(得分:0)

请使用ModelState.AddModelError(string.Empty,“这是一条错误消息”); 和@ Html.ValidationSummary(true);

这样可行。