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.
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:
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 workModelState.AddModelError("", "The user name or password provided is incorrect.");
- worksIt could be a few different things off the top of my head. First off you may not be including the required JavaScript. You may not need all of these but i include these in almost all of my layout views.
Also, could you show the code for your partial view? If you are referencing values that are inside a child class in your model the validation can act a little wonky sometimes.
Lastly, this sounds silly but as you did not post the code for your login model make sure you are using the proper data annotations for the values that you want the validation to show up for.
Remove the true argument in
@Html.ValidationSummary()