Nick Nick - 27 days ago 17
ASP.NET (C#) Question

MVC 5 Multiple HtmlHelper.ValidationSummary on one page

I have two forms on my login page:


  • Register

  • Login



They are defined as:

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { role = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "");
// form controls etc...
}


and

@using (Html.BeginForm("Register", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { role = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "");
// form controls etc...
}


The problem occurs when I submit one of the forms and there is a validation error, both Validation Summaries display the errors.

There are various overloads for the ValidationSummary method (https://msdn.microsoft.com/en-us/library/system.web.webpages.html.htmlhelper.validationsummary(v=vs.111).aspx), however none of them solve this issue.

The desired functionality is:


  • When there is a validation error on the Login form, the errors are displayed on the Login form's ValidationSummary, and the ValidationSummary on the Register form is blank

  • When there is a validation error on the Register form, the errors are displayed on the Register form's ValidationSummary, and the ValidationSummary on the Login form is blank


Answer

ValidationSummary simply displays whatever errors are in ModelState (either just model-level or all errors, depending on what you pass for that param). However, importantly, there's no differentiation here between multiple forms. Regardless of which form has errors, ValidationSummary will cause those errors to appear, as you've seen.

The only way around this is to conditionally display ValidationSummary. All you need is some post value that you can check which will only exist in one of the forms. This could be just a property that one has and the other doesn't or you can add a specific value by either using a hidden input or adding a name attribute to your button. Then:

@if (ModelState.HasKey("MyUniqueKey"))
{
    @Html.ValidationSummary(true)
}