开发者

Specify validation summary on multiple forms

开发者 https://www.devze.com 2023-02-17 23:57 出处:网络
I have 2 forms on a page as follows: @using (Html.BeginForm()) { @Html.ValidationSummary() @Html.Label(\"code\", \"Confirmation Code\")

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开发者_StackOverflow 2 validation summary being displayed. How do I get the validation summary to target its own?


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


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

for more details check this blog post


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消