ModelState errors not showing in partialview form

Relatively new to ASP.NET and I’m having issues with validations within partials. At the moment, on submit even when Model.IsValid is false the errors aren’t being displayed within the partial view form. The Modelstate is passing the errors back to the parent view from the controller which I have break pointed to see in the ViewData.

However, I’m running into a roadblock on passing the ModelState errors to the partials. What am I missing to display the validation errors in my partial view?

ViewModel:

[Display(Name = "Email")] [Required(ErrorMessage = "Email is required")] public string Email { get; set; }  [Display(Name = "Password")] [Required(ErrorMessage = "Password is required")] public string Password { get; set; } 

Controller:

public ActionResult SaveEmail(AccountSettingsVM viewModel) {   if (ModelState.IsValid)   {     var saveEmail = _service.SaveEmail(viewModel);      if (saveEmail)     {       return Json(new { IsSuccess = true, Message = "Email Successfully Changed" });     }     else     {       return Json(new { IsSuccess = true, Message = "There was an error processing your request." });     }   }    return View("Index", viewModel) } 

Index View:

@model AccountSettingsVM  <div class="tab-content">     <div class="tab-pane">         @Html.Partial("~/Views/Customer/AccountSettings/_EmailSettings.cshtml", Model)     </div> </div> 

Partial View:

<div class="col-md-5 col-centered">      @using (Html.BeginForm("SaveEmail", "AccountSettings", FormMethod.Post, new { id = "email-form" }))     {         @Html.AntiForgeryToken();          <div class="form-group">             @Html.LabelFor(model => model.Email, new { @class = "control-label" })             @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })             @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })         </div>          <div class="form-group">             @Html.LabelFor(model => model.Password, new { @class = "control-label" })             @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })             @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })         </div>         <button id="btnChangeEmail" type="button" class="btn btn-primary btn-block">Save Changes</button>     } </div> 

Scripts/Ajax:

<script src="~/Content/light/js/jquery.validate.min.js" type="text/javascript"></script> <script src="~/Content/light/js/jquery.validate.unobtrusive.js" type="text/javascript"></script>  $('#btnChangeEmail').on('click', function (e) {     e.preventDefault();     const url = `/AccountSettings/SaveEmail`      const ajax = $.ajax({         url: url,         type: 'POST',         data: $('#email-form').serialize()     });      ajax.done(response => {         if (response.IncorrectPassword) {             $incorrectPass.show()         } else if (response.IsSuccess) {             $incorrectPass.hide()             $('#emailMdl-title-span').addClass("text-success");             $('#emailMdl-title-span').html("<i class='fa fa-check-circle text-success'></i>&nbsp;&nbsp;<strong>Success</strong>");             $('#CreateAccountResults').html(`<strong>${response.Message}</strong>`);             $('#resultsModal').modal();         }     }) }) 
Add Comment
1 Answer(s)

In this case it wasn’t that it was losing Modelstate to view, I was doing an AJAX request and not re-rendering the html with the response that would have the updated errors. Solution to my problem:

Controller

return PartialView("~/Views/Customer/AccountSettings/_ChangeEmailForm.cshtml", vm); 

AJAX

if (response.IsSuccess) {  } else {   $('#email-form').html(response) } 
Answered on August 30, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.