什么时候应该使用Html.Displayfor在MVC [英] When should I use Html.Displayfor in MVC
问题描述
我是新来的MVC,并知道如何使用 Html.Displayfor()
,但我不知道什么时候使用它?
I am new to MVC and know how to use Html.Displayfor()
, but I don't know when to use it?
任何想法?
推荐答案
的 DisplayFor
帮手呈现给定类型对应的显示模板。如果你想以某种方式个性化这个模板,你应该使用它的例子。或集合属性。当与集合属性中使用的相应的模板将自动被渲染为集合中的每个元素
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.
下面是它如何工作的:
@Html.DisplayFor(x => x.SomeProperty)
将呈现的<一个href=\"http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html\">default模板给定类型。例如,如果你装饰了您的视图模型属性与一些格式化选项,将尊重这些选项:
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; }
而当你认为你用DisplayFor助手将考虑到这种格式,而如果使用简单的呈现属性 @ Model.SomeProperty
也不会尊重这个自定义格式。
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.
但dn't知道什么时候使用它?
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)
而不是:
@Model.SomeProperty
这篇关于什么时候应该使用Html.Displayfor在MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!