What is the @Html.DisplayFor syntax for?
Asked Answered
E

6

253

I understand that in Razor, @Html does a bunch of neat things, like generate HTML for links, inputs, etc.

But I don't get the DisplayFor function...

Why would I write:

@Html.DisplayFor(model => model.Title)

when I could just write:

@Model.Title
Espouse answered 15/6, 2011 at 23:30 Comment(0)
M
248

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

If it can't find any, I suppose it invokes .ToString().


If you don't know about display templates, they're partial views that can be put in a DisplayTemplates folder inside the view folder associated to a controller.


Example:

If you create a view named String.cshtml inside the DisplayTemplates folder of your views folder (e.g Home, or Shared) with the following code:

@model string

@if (string.IsNullOrEmpty(Model)) {
   <strong>Null string</strong>
}
else {
   @Model
}

Then @Html.DisplayFor(model => model.Title) (assuming that Title is a string) will use the template and display <strong>Null string</strong> if the string is null, or empty.

Moniquemonism answered 15/6, 2011 at 23:36 Comment(7)
Seems pointless to me, in most cases, to use DisplayFor for primitive types. For example, DateTime would display date/time even if the time part was useless. If you could specify a format string of "{0:d}" for a DateTime type in the property's attributes on the Model, DisplayFor could possibly be more useful.Plaza
@Plaza you can. See Daveo's answer.Moniquemonism
You could add a jQuery date picker to the EditorFor template for a DateTime datatype to always show a date picker in forms for example.Tunstall
It seems to me like it's over-engineering to use it in general, but that you should use it when you want to format the output for certain model attributes. Helpful question and answer guys, thanks. +1s all round.Ellita
what happens if you have two models with the same name?Nidify
@BertrandMarron Hi I know this is an old post but I would like to know if you can provide us with the reference please? Thanks!Poland
@Poland Take a look at this. Also look at Daveo's answerRhamnaceous
N
82

I think the main benefit would be when you define your own Display Templates, or use Data annotations.

So for example if your title was a date, you could define

[DisplayFormat(DataFormatString = "{0:d}")]

and then on every page it would display the value in a consistent manner. Otherwise you may have to customise the display on multiple pages. So it does not help much for plain strings, but it does help for currencies, dates, emails, urls, etc.

For example instead of an email address being a plain string it could show up as a link:

<a href="mailto:@ViewData.Model">@ViewData.TemplateInfo.FormattedModelValue</a>
Newmint answered 15/6, 2011 at 23:41 Comment(0)
E
32

DisplayFor is also useful for templating. You could write a template for your Model, and do something like this:

@Html.DisplayFor(m => m)

Similar to @Html.EditorFor(m => m). It's useful for the DRY principal so that you don't have to write the same display logic over and over for the same Model.

Take a look at this blog on MVC2 templates. It's still very applicable to MVC3:

http://www.dalsoft.co.uk/blog/index.php/2010/04/26/mvc-2-templates/


It's also useful if your Model has a Data annotation. For instance, if the property on the model is decorated with the EmailAddress data annotation, DisplayFor will render it as a mailto: link.

Elayneelazaro answered 15/6, 2011 at 23:39 Comment(4)
@Html.DisplayFor(m => m) can also be simplified to just @Html.DisplayForModel().Unsophisticated
What is the lamda expression (m=>m)? What is the first m represent?Wiener
the first m is the name of the parameterKhartoum
@magic-c0d3r the first m is the page's Model object. That's what's used in the labmda expressionFiles
R
4

In general if it is used for just one property it appears that the generated HTML is the same.

For example this code

<td>@Html.DisplayFor(modelItem=>item.Genre.Name)</td>         
<td>@item.Genre.Name, This is direct from Item</td>

generates this HTML

<td>myClassNameProperty</td>
<td>myClassNameProperty, This is direct from Item</td>

At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least

i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below

@item.Genre.Name
@item.Genre.Id
@item.Genre.Description

and so on depending on number of properties.

3rd party edit

From html-helpers documentation:

An HTML Helper is just a method that returns a string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML and tags. You also can use HTML Helpers to render more complex content such as a tab strip or an HTML table of database data.

To render more complex html mvc custom html templates or custom tag helpers in asp.net core are used.

Rick answered 3/11, 2014 at 9:23 Comment(0)
C
1

The main difference between @Html.DisplayFor(model => model.Title) and @Model.Title

Html.DisplayFor() is a strongly typed method that can be used to display the value of a model property in a view. It is used to display the value of the property in a way that is appropriate for the data type of the property. It will also respect any DataAnnotations attributes applied to the property and display the property accordingly.

@Model.Title directly outputs the value of the "Title" property to the view. It does not use any formatting or data annotation attribute to display the value.

In summary,

@Html.DisplayFor(model => model.Title) is a more robust and safe way to display a property, since it takes care of formatting and validation, while @Model.Title is a simple and quick way to output a property value.

Cannikin answered 19/1, 2023 at 4:16 Comment(0)
T
0

Would like to elaborate with a scenario on the reason to use DisplayFor rather than simply using the model value. The application/significance of what others have mentioned that "DisplayFor uses display template to render", is for example for a boolean, this displays a checkbox

@Html.DisplayFor(model => model.IsBooleanTrue)

Sidenote: EditorFor would display the same checkbox that is not disabled

Documentation: https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.html.displayextensions.displayfor?view=aspnet-mvc-5.2 (no examples in there unfortunately)

Titular answered 18/1, 2023 at 22:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.