I have two forms on my login page:
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:
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)
}
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