ModelState.AddModelError - no error shown

流过昼夜 提交于 2020-01-24 06:11:45

问题


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.



来源:https://stackoverflow.com/questions/15504348/modelstate-addmodelerror-no-error-shown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!