What's the point of Html.DisplayTextFor()?

Sean Cain picture Sean Cain · Aug 13, 2010 · Viewed 25.1k times · Source

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

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

As opposed to...

<%: Model.Email %> 

Answer

Yngve B-Nilsen picture Yngve B-Nilsen · Aug 13, 2010

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.