tags:

views:

160

answers:

2

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?

+2  A: 

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 ) %>
tvanfosson
Quick and to the point. :)
BobbyShaftoe
+10  A: 

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) %>
Brant Bobby
Ah, right, because the first parameter "Quantity" in the previous HtmlHelper methods is what would attempt to bind back when the values are submitted. Now I get it.
Nick DeVore