Asp.Net Mvc 3 Client Validation, Attributes genera

2020-06-16 01:44发布

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

2条回答
男人必须洒脱
2楼-- · 2020-06-16 01:45

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();
}
查看更多
一纸荒年 Trace。
3楼-- · 2020-06-16 01:51

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

查看更多
登录 后发表回答