开发者

The difference between html control and controFor

What is the difference between mvc HTML.Control and ControlFor (TextBox,开发者_运维知识库 checkbox etc)..


One is strongly typed. If you have a view that expects a model of type Customer with a property "CustomerName", you can render the value with either way

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

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

With the second method (lambda expression), you avoid magic strings. You also have the ability to inspect ModelMetadata to perform additional customizations.

Read about Model metadata here:

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


The For versions of the HTML helper methods take properties as strongly-typed lambda expressions instead of strings.

For example, the following to statements are equivalent:

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

However, if you rename the Description property, the TextBoxFor call will give a compiler error, whereas the TextBox call will not fail until you visit that page.


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

Simply put, HTML.ControlFor is strongly typed, which allows use of lambda expressions and automatically takes the nameof the property specified as the name/id of the control.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜