When should I use Html.Displayfor in MVC

2019-01-06 17:13发布

问题:

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

Any idea?

回答1:

The DisplayFor helper renders the corresponding display template for the given type. You should use it for example if you wanted to personalize somehow this template. Or with collection properties. 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; }

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

but dn't know when to use it?

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

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

instead of:

@Model.SomeProperty


回答2:

I'm extending @Darin's answer.

Html.DisplayFor(model => model.SomeCollection) will iterate over items in SomeCollection and display the items using DisplayFor() recursively.