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?
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.
Html. DisplayFor() will render the DisplayTemplate that matches the property's type.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With