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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With