ModelState.AddModelError - no error shown

2019-06-28 00:09发布

问题:

I'd like to set an error message for an email field after an exception has been caught in my controller:

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

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

The error message should now be displayed in my view:

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

But nothing is shown in this case. :( What did I do wrong?

回答1:

When adding model errors the correct separator when working with complex objects is the dot . and not the unserscore _

So the following call should work:

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


回答2:

Please use ModelState.AddModelError(string.Empty, "This is an error message"); and @Html.ValidationSummary(true);

This will work.