Specify validation summary on multiple forms

2019-01-18 18:24发布

问题:

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?

回答1:

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()
}


回答2:

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

for more details check this blog post



回答3:

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.



回答4:

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.



回答5:

Explicitly define the action and controller in form if you have multiple forms in 1 view, like

@using (Html.BeginForm("SendCode", "Auth"))
{
    @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" />
}

Believing that for both forms you have different actions.