Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState.AddModelError - no error shown

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?

like image 679
mosquito87 Avatar asked Feb 18 '23 03:02

mosquito87


1 Answers

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");
like image 71
nemesv Avatar answered Mar 07 '23 21:03

nemesv