4

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

...
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>
...

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

4

2 回答 2

8

添加模型错误时,使用复杂对象时正确的分隔符是点.而不是 unsercore_

所以下面的调用应该有效:

ModelState.AddModelError("Useraccount.Email", "This is an error message");
于 2013-03-19T16:25:19.317 回答
0

请使用 ModelState.AddModelError(string.Empty, "This is an error message"); 和@Html.ValidationSummary(true);

这将起作用。

于 2014-01-31T05:03:08.760 回答