Asp.Net Mvc 3 Client Validation, Attributes genera

2020-06-16 01:29发布

问题:

Asp.net Mvc3 ads some custom attributes like "data-val-required" on input elements to perform validation. I know all theory behind this, how it works.

What i want to know is :

When I create my form inside " @using (Html.BeginForm())" it produces custom attributes, but it doesn't create those attributes when i place my form between plain "<form>" tag.

below is a demo i have created to demonstrate what iam saying

Razor Code, form inside BefingForm()

 @using (Html.BeginForm()) {
                @Html.EditorFor(model => model.EmailAddress)
                @Html.ValidationMessageFor(model => model.EmailAddress)
}

generated Html contains "data-val-required" as attribute shown below

<input type="text" value=""  data-val-required="The Email Address field is required."  data-val-email="my message">

Razor Code Form inside pure Html Tag

<form action="/Account/Register" method="post">
            @Html.EditorFor(model => model.EmailAddress)
            @Html.ValidationMessageFor(model => model.EmailAddress)
</form>

generated Html doesnt contain "data-val-required" attribute shown below

<input type="text" value=""  gtbfieldid="44">

My question is how can i ask MVC to add those attributes even form is placed in side pure html tags

回答1:

I believe BeginForm method internally assigns a formcontext object to viewCotnext's property FormContext. If you do not want to use plain html form tags you have to do it manually like

<%
    this.ViewContext.FormContext = new FormContext();
%>

and in razor it would probably be

@{
    this.ViewContext.FormContext = new FormContext();
}


回答2:

Problem here is that internally Html.BeginForm is flagged by Html.EnableClientValidation() to create FormContext that will store client-side validation metadata. Now, any HTML helper method that renders validation message also registers appropriate client-side validation metadata in FormContext. The result is what you get if you use helper. However, if you try to use HTML syntax and not helpers, the FormContext is never registered and therefore your validation is never added.

Regards,

Huske