Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 784
Andre Figueiredo Avatar asked Dec 18 '13 18:12

Andre Figueiredo


People also ask

What is HTML DisplayFor?

DisplayFor() The DisplayFor() helper method is a strongly typed extension method. It generates a html string for the model object property specified using a lambda expression.

What is DisplayFor?

Html. DisplayFor() will render the DisplayTemplate that matches the property's type.

What is ASP NET MVC Razor?

ASP.NET MVC 5 for Beginners Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.

What is razor view in asp net core?

Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET Core MVC, views are .cshtml files that use the C# programming language in Razor markup. Usually, view files are grouped into folders named for each of the app's controllers.


1 Answers

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.

like image 98
Ant P Avatar answered Nov 27 '22 22:11

Ant P