Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

As opposed to...

<%: Model.Email %>  
like image 379
Sean Cain Avatar asked Aug 13 '10 03:08

Sean Cain


2 Answers

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.

like image 132
Yngve B-Nilsen Avatar answered Oct 29 '22 20:10

Yngve B-Nilsen


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.

like image 21
JcMaltaDev Avatar answered Oct 29 '22 19:10

JcMaltaDev