Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Mvc 3 Client Validation, Attributes generation

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

like image 726
Praveen Prasad Avatar asked Jul 11 '11 22:07

Praveen Prasad


1 Answers

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();
}
like image 59
Muhammad Adeel Zahid Avatar answered Nov 08 '22 23:11

Muhammad Adeel Zahid