我什么时候应该在 MVC 中使用 Html.Displayfor [英] When should I use Html.Displayfor in MVC

查看:37
本文介绍了我什么时候应该在 MVC 中使用 Html.Displayfor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 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. 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.

这是它的工作原理:

@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; }

在您看来,当您使用 DisplayFor 助手时,它将通过考虑此格式来呈现属性,而如果您仅使用 @Model.SomeProperty,它会不会尊重这种自定义格式.

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.

但不知道什么时候用?

当您想显示视图模型中的值时,请始终使用它.始终使用:

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

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

代替:

@Model.SomeProperty

这篇关于我什么时候应该在 MVC 中使用 Html.Displayfor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆