2

Take into account a model class with a property PartnerName on it.

In this case looks like these two code produce the same results:

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

Is there any advantages in using one against the other? Because the first one is way more cleaner.

Edit And just to be clear I'm talking about this specific overload.

Vitor Canova
  • 3,918
  • 5
  • 31
  • 55
  • 2
    DisplayFor will use any available display template for the type. If you have a specific template eg for `Customer`, with special layout and colouring, it will use that. If none is found, it will use the default template which simply renders the value as text. Accessing the value using Model will only render the text representation of the value, ie the result of calling `ToString()` – Panagiotis Kanavos Apr 01 '16 at 12:43
  • 1
    @PanagiotisKanavos Why not this answer? – asdf_enel_hak Apr 01 '16 at 12:47
  • 2
    Because I'm certain there are dozens of duplicates and at *least* one good tutorial page in the ASP.NET MVC site. – Panagiotis Kanavos Apr 01 '16 at 12:53
  • Thanks @PanagiotisKanavos. Missed that it would take a template as "convention". Only saw the other overloads. – Vitor Canova Apr 01 '16 at 12:56

1 Answers1

5

When you display a value using @Model.PartnerName it places the plain value into your HTML without any surrounding markup. When you use @Html.DisplayFor(m => m.PartnerName) you are invoking a DisplayTemplate to render the object.

These DisplayTemplates usually contain markup to make sure the value is displayed in a certain way. You can also create custom DisplayTemplates so you can always, for example, display your strings inside fancy boxes with borders and colors.

Check out this article for creating custom DisplayTemplates. http://www.codeguru.com/csharp/.net/net_asp/mvc/using-display-templates-and-editor-templates-in-asp.net-mvc.htm

DunningKrugerEffect
  • 603
  • 1
  • 5
  • 18