Nick DeVore
Nick DeVore

Reputation: 10166

Why do Strongly Typed Html Helpers help me?

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?

Upvotes: 3

Views: 1590

Answers (3)

Ramachandran
Ramachandran

Reputation: 41

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"}) 

Upvotes: 0

Brant
Brant

Reputation: 15334

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) %>

Upvotes: 14

tvanfosson
tvanfosson

Reputation: 532465

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 ) %>

Upvotes: 3

Related Questions