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

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.

Leave a Comment