Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use Html.Displayfor in MVC

I am new to MVC and know how to use Html.Displayfor(), but I don't know when to use it?

Any idea?

like image 840
BreakHead Avatar asked Feb 27 '12 12:02

BreakHead


People also ask

What is the purpose of 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 the difference between DisplayNameFor and DisplayFor in MVC?

DisplayNameFor(m => m.Name) does not. DisplayFor displays the value for the model item and DisplayNameFor simply displays the name of the property?

What are HTML helpers in MVC?

In MVC, HTML Helper can be considered as a method that returns you a string. This string can describe the specific type of detail of your requirement. Example: We can utilize the HTML Helpers to perform standard HTML tags, for example HTML<input>, and any <img> tags.

What is HTML raw in MVC?

The Html. Raw Helper Method is used to display HTML in Raw format i.e. without encoding in ASP.Net MVC Razor. Configuring Bundles. Please refer the following article for complete information on how to configure Bundles in ASP.Net MVC project. Using Bundles (ScriptBundle) in ASP.Net MVC Razor.


1 Answers

The DisplayFor helper renders the corresponding display template for the given type. For example, you should use it with collection properties or if you wanted to somehow personalize this template. When used with a collection property, the corresponding template will automatically be rendered for each element of the collection.

Here's how it works:

@Html.DisplayFor(x => x.SomeProperty) 

will render the default template for the given type. For example, if you have decorated your view model property with some formatting options, it will respect those options:

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")] public DateTime SomeProperty { get; set; } 

In your view, when you use the DisplayFor helper, it will render the property by taking into account this format whereas if you used simply @Model.SomeProperty, it wouldn't respect this custom format.

but don't know when to use it?

Always use it when you want to display a value from your view model. Always use:

@Html.DisplayFor(x => x.SomeProperty) 

instead of:

@Model.SomeProperty 
like image 198
Darin Dimitrov Avatar answered Sep 29 '22 10:09

Darin Dimitrov