Shawn Mclean
Shawn Mclean

Reputation: 57469

Specify validation summary on multiple forms

I have 2 forms on a page as follows:

@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    @Html.Label("code", "Confirmation Code")
    @Html.TextBox("code")
    <input type="submit" value="Go" />
}
@using (Html.BeginForm("SendConfirmation", "Auth"))
{
    @Html.ValidationSummary()
    @Html.Label("email", "Email")
    @Html.TextBox("email")
    <input type="submit" value="Resend" />
}

If SendConfirmation throws an error, there are 2 validation summary being displayed. How do I get the validation summary to target its own?

Upvotes: 30

Views: 9971

Answers (4)

Dan Diplo
Dan Diplo

Reputation: 25339

Give the submit button a unique name on both your forms, like so:

@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    @Html.Label("code", "Confirmation Code")
    @Html.TextBox("code")
    <input type="submit" name="login-top" value="Go" />
}
@using (Html.BeginForm("SendConfirmation", "Auth"))
{
    @Html.ValidationSummary()
    @Html.Label("email", "Email")
    @Html.TextBox("email")
    <input type="submit" name="login-main" value="Resend" />
}

Then you can check whether a particular form has been submitted by checking the value of the request for the key that corresponds to the submit button and then conditionally display the validation summary ie. in the top form you would add:

if (Request.Form.AllKeys.Contains("login-top"))
{
    @Html.ValidationSummary()
}

Upvotes: 21

Nick Albrecht
Nick Albrecht

Reputation: 16928

Html.ValidationSummary() does not need to be inside of your form element and you only need it the once int most cases. I'd move it outside of your two forms, something like just above your main body content and that should give you the desired effect. I believe in my last app I placed it in the Layout file.

Upvotes: 3

Rob Carroll
Rob Carroll

Reputation: 377

In order to accomplish this you need to separate the two forms, put each one in a partial view, and return the partial view on submit if the validation fails. Change your action result to return a partial result.

the partial views can be rendered in the page using the following:

@Html.partial("_PartialView")

or this way if you need to pass a model

@Html.partial("_Partial", Model)

You can't have two validation summaries on the same page any other way.

Upvotes: 1

Mandoleen
Mandoleen

Reputation: 2661

the solution is to draw the validation summary only when you validate your form

for more details check this blog post

Upvotes: 6

Related Questions