C# 我什么时候应该在 MVC 中使用 Html.Displayfor
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9465376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When should I use Html.Displayfor in MVC
提问by BreakHead
I am new to MVC and know how to use Html.Displayfor(), but I don't know when to use it?
我是 MVC 的新手并且知道如何使用Html.Displayfor(),但我不知道什么时候使用它?
Any idea?
任何的想法?
采纳答案by Darin Dimitrov
The DisplayForhelper 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.
该DisplayFor助手呈现给定类型对应的显示模板。例如,您应该将它与集合属性一起使用,或者如果您想以某种方式个性化此模板。当与集合属性一起使用时,将自动为集合的每个元素呈现相应的模板。
Here's how it works:
这是它的工作原理:
@Html.DisplayFor(x => x.SomeProperty)
will render the default templatefor 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 DisplayForhelper, 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.
在您看来,当您使用DisplayForhelper 时,它将通过考虑此格式来呈现属性,而如果您只使用@Model.SomeProperty,则不会尊重此自定义格式。
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
回答by Zruty
I'm extending @Darin's answer.
我正在扩展@Darin 的回答。
Html.DisplayFor(model => model.SomeCollection)will iterate over items in SomeCollectionand display the items using DisplayFor()recursively.
Html.DisplayFor(model => model.SomeCollection)将遍历项目SomeCollection并使用DisplayFor()递归显示项目。

