views:

175

answers:

3

Is there a good reason to use the strongly typed html helper...

<%: Html.DisplayTextFor(model => model.Email) %>

As opposed to...

<%: Model.Email %> 
+2  A: 

Well, DisplayTextFor will not break if you do not pass in a model (or pass null). Model.Email will throw an exception on null. So, DisplayTextFor is more robust.

The point of the strongly typed helpers is to allow greater compile time checking. This is very handy when refactoring.

DisplayTextFor allows using a consistent construct (with the other strongly typed helpers) throughout the page. Some people might find that more appealing.

DisplayTextFor also allows you to pass the names of templates and fields as parameters.

Justin
+4  A: 

DisplayTextFor will also get called during "DisplayFor" and "EditFor" execution. This will ensure that any templated helpers will display the text using the correct Templated Helpers if set ... so a change to the single templated helper will propogate through all displays of that text item ... simple display, edit form, create forms etc etc.

JcMalta
So are you saying it's sort of like a .ToString() for the model property? If so, I could see that being helpful if the model property were a complex type.
seanp
+2  A: 

Consider the following Model:

public class MyModel
{
    public string Name { get; set; }

    [DisplayFormat(NullDisplayText = "No value available!")]
    public string Email { get; set; }

}

in my view:

<%= Html.DisplayTextFor(m => m.Email) %>

<%: Model.Email %>

The first line will display "No value available" if we leave the Email to be 'null' whereas the second line will not display anything.

Conclusion: Html.DisplayTextFor will take into consideration the DataAnnotations on your properties, <%: Model.Email %> will not. Also <%: Model.Email %> will throw an "Object reference error" when the value is null, but <%= Html.DisplayTextFor %> wont.

Yngve B. Nilsen