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

前端 未结 3 613
情话喂你
情话喂你 2020-12-28 11:59

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

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

As opposed to...

3条回答
  •  星月不相逢
    2020-12-28 12:41

    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.

提交回复
热议问题