Direct Model.Property vs. Html Helper DisplayFor in razor

Is there a reason to use preferably one of them:

@Model.Property @Html.DisplayFor(m => m.Property) 

I have never been at a crossroads where one works differently.

Is there any difference?

+6
source share
1 answer

Model.Property - as you know, it simply writes out the value of the corresponding property. Html.DisplayFor(m => m.Property) , on the other hand, will invoke a display template that can display different markup around the property value.

For example, you can define a display template as follows:

 @model String <div class="property-wrapper"> <p>@Model.Property</p> </div> 

Surrounding divs will be displayed around the property value when using DisplayFor (if a display template is selected, which usually means that it has a file name that matches the property type, is specified in the UIHint attribute for the property or explicitly specified in the DisplayFor call.

You also have access to the model metadata in the display templates, which means you can do something like this:

 <div class="property-label"> @Html.DisplayNameForModel() </div> <div class="property-value"> @Model.Property </div> 

Display templates give you great flexibility and reusability. The best way to learn this is to start creating custom templates and see where it takes you.

+11
source

All Articles