Difference between html control and controFor

What is the difference between mvc HTML.Control and ControlFor (TextBox, checkbox, etc.).

+2


a source to share


3 answers


One of them is strongly typed. If you have a view that expects a model of type Customer with a "CustomerName" property, you can display that value anyway

<%=Html.Label("CustomerName") %> 

<%=Html.LabelFor(a => a.CustomerName) %> //strongly typed

      

In the second method (lambda expression), you avoid magic strings. You also have the option to check ModelMetadata for additional customizations.



Read about model metadata here:

http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html

+2


a source


The HTML helper versions For

accept properties as strongly typed lambda expressions instead of strings.

For example, the following statements for operators are equivalent:



<%=Html.TextBox("Description") $>
<%=Html.TextBoxFor(m => m.Description) $>

      

However, if you rename the property Description

, the call TextBoxFor

will give a compiler error, whereas the call TextBox

will not work until you visit this page.

+2


a source


The following article explains the difference in general:

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

In simple terms, HTML.ControlFor is strongly typed, which allows lambda expressions and automatically takes the name of the property specified as the name / ID of the control.

+1


a source







All Articles