开发者

Why do Strongly Typed Html Helpers help me?

开发者 https://www.devze.com 2022-12-16 05:52 出处:网络
开发者_JAVA技巧I read ScottGu\'s explanation on Strongly Typed Html Helpers and I understand that it gives me the ability to do better compile time checking of views.I was under the impression that I
开发者_JAVA技巧

I read ScottGu's explanation on Strongly Typed Html Helpers and I understand that it gives me the ability to do better compile time checking of views. I was under the impression that I already had this when I used the model.PropertyName in the MVC1 Html.TextBox helper, but apparently that is not true. So, how does using a lambda expression do this better for me?


Consider the syntax of the existing HTML helper methods:

<%= Html.TextBox("Quantity", Model.Quantity) %>

If you rename the Quantity property on your object to "CurrentQuantity", the generated <input> element will still have name="Quantity" specified, and model binding will break if you don't remember to change that first parameter.

By using a lambda expression to specify the name of the element, an incorrect or misspelled property name becomes a compilation error.

<!-- No magic strings here! -->
<%= Html.TextBoxFor(model => model.CurrentQuantity) %>


The improvement comes when you specify the name of the property to the helper. With strongly typed helpers, it uses the lambda expression instead of the property name to determine which property value to use.

<%= Html.TextBox( "Name" ) %>

vs

<%= Html.TextBox( m => m.Name ) %>


Textbox does not give compile time error when you wrongly mentioned the property name. it will throw run time exception. TextBoxFor is a genetic method so it will give compile time error when you wrongly mentioned the property name. TextBoxFor will be helpful when we append two property names in view

@Html.TextBox( "Name" ,"value",new { @class="class"}) 

vs

@Html.TextBoxFor( m => m.Name, new { @id="txtValue"}) 
0

精彩评论

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