ValidationSummary inside a partial view not showing errors
asp.net-mvc-4, model, validation
Solution
I found the problem.
I was passing a new ViewData in the RenderPartial which was overriding the ViewData of the parent view, so the model state was lost, as explained here: Pass Additional ViewData to an ASP.NET MVC 4 Partial View While Propagating ModelState Errors.
Changing the main view to:
@model Portal.Models.LoginModel
@{
ViewData.Add("actionName", "Login");
ViewData.Add("controllerName", "Account");
Html.RenderPartial("_LoginFormNoRegistration", Model, ViewData);
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Did the trick!
Also, if you want to show a general error message for the model in the `validationsummary`, be sure to add the error with an empty string as key:
`ModelState.AddModelError("error", "The user name or password provided is incorrect.");` - doesn't work
`ModelState.AddModelError("", "The user name or password provided is incorrect.");` - works
Problem
I have a partial view like this (simplified): ``` @model Portal.Models.LoginModel <div class="login-container k-block"> <section id="login-form" class=""> @using (Html.BeginForm(actionName, controllerName, new { ReturnUrl = ViewBag.ReturnUrl })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset id="login-form-list-items"> <ol> <li> @Html.LabelFor(m => m.CardNumber) @Html.TextBoxFor(m => m.CardNumber, new { @class="k-textbox"}) <div class="k-error-colored"> @Html.ValidationMessageFor(m => m.CardNumber) </div> </li> <li> @Html.LabelFor(m => m.Pin) @Html.PasswordFor(m => m.Pin, new { @class="k-textbox"}) <div class="k-error-colored"> @Html.ValidationMessageFor(m => m.Pin) </div> </li> <input id="login-input-submit" class="k-button" type="submit" value="Enter" /> </fieldset> </div> ``` And in my `login` view I call this partial view like: ``` @model Portal.Models.LoginModel @Html.Partial("_LoginFormNoRegistration", Model, new ViewDataDictionary { { "actionName", "Login" }, { "controllerName", "Account" } }) @section Scripts { @Scripts.Render("~/bundles/jqueryval") } ``` The problem is that when the `login` method in the controller adds an error like: ``` public ActionResult Login(LoginModel model, string returnUrl) { //... // If we got this far, something failed, redisplay form ModelState.AddModelError("", "The user name or password provided is incorrect."); return View(model); } ``` The message is not show in the validation summary... I don't understand why... What could be the problem? Some javascript library missing? Update I also found that the form generated as the `novalidate` attribute set: ``` <form action="/" method="post" novalidate="novalidate"> //... </form> ``` I don't know why.