Andre Figueiredo
Andre Figueiredo

Reputation: 13425

Direct Model.Property versus Html Helper DisplayFor in Razor

Is there a reason to use preferably one of these:

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

I never arrived in a crossroad where one works differently from the other.

There is any difference?

Upvotes: 7

Views: 6439

Answers (1)

Ant P
Ant P

Reputation: 25221

Model.Property - as you know - will just write out the value of the property in question. Html.DisplayFor(m => m.Property), on the other hand, will call a display template, which can render out other markup around the property value.

For example, you might define a display template like so:

@model String

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

The surrounding divs will be rendered around the value of the property when using DisplayFor (if the display template is selected, which typically means it has a filename matching the property's type, is specified in the UIHint attribute for the property, or is explicitly specified in the call to DisplayFor.

You also have access to model metadata in your display templates, meaning you can do something like this:

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

<div class="property-value">
    @Model.Property
</div>

Display templates give you a huge amount of flexibility and reusability. The best way to explore this is to start building custom templates and see where it takes you.

Upvotes: 13

Related Questions