MVC 4数据注释"显示"属性 [英] MVC 4 Data Annotations "Display" Attribute

查看:77
本文介绍了MVC 4数据注释"显示"属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始接触MVC 4(的Razor视图引擎)。 (我认为这可能适用于MVC 3和更早的为好。)我想知道是否有使用视图而不只是直接在HTML编写一个字符串中DisplayAttribute数据标注任何好处。举例来说,如果我有以下型号:

I am starting out with MVC 4 (Razor view engine). (I believe this may apply to MVC 3 and earlier as well.) I am wondering if there is any benefit to using the DisplayAttribute data annotation within a view versus just writing a string directly in the HTML. For example, if I had the following model:

public class Thing
{
    public string WildAndCrazyProperty { get; set; }
}

...会有任何好处的注释属性为:

...would there be any benefit in annotating the property as:

    [Display(Name = "Wild and Crazy")]
    public string WildAndCrazyProperty { get; set; }

...并有我的标记是:

...and having my markup be:

<html>
    <body>
        <div>@Html.DisplayNameFor(modelItem => modelItem.WildAndCrazyProperty)</div>
        <div>@Html.DisplayFor(modelItem => modelItem.WildAndCrazyProperty)</div>
    </body>
</html>

...对不具有注释,以及这样做的:

...versus not having the annotation, and doing:

<html>
    <body>
        <div>Wild and Crazy</div>
        <div>@Html.DisplayFor(modelItem => modelItem.WildAndCrazyProperty)</div>
    </body>
</html>

我还没有在这种情况下提到的 Html.LabelFor 的原因是因为属性的数据被显示为静态的页面上(即不可编辑)的文本。数据永远不会编辑这个页面上,所以没有必要对我来说,使用 Html.TextBoxFor 内的第二&​​LT; D​​IV&GT;随后使用 Html.LabelFor 与该文本框的标签正确关联。

The reason I haven't mentioned Html.LabelFor in this case is because the property's data is being displayed as static (i.e. non-editable) text on the page. The data will never be editable on this page, so there is no need for me to use Html.TextBoxFor within the second <div> and subsequently use the Html.LabelFor to properly associate a label with that text box.

推荐答案

如果两种不同的意见都共享同一个模型(例如,说不定是移动输出,一个是常规的),它可能是不错的字符串住在同一个地方:作为视图模型元

If two different views are sharing the same model (for instance, maybe one is for mobile output and one is regular), it could be nice to have the string reside in a single place: as metadata on the ViewModel.

此外,如果你有这样的必要不同的显示模式的继承版本,它可能是有用的。例如:

Additionally, if you had an inherited version of the model that necessitated a different display, it could be useful. For instance:

public class BaseViewModel
{
 [Display(Name = "Basic Name")]
 public virtual string Name { get; set; }
}

public class OtherViewModel : BaseViewModel
{
 [Display(Name = "Customized Inherited Name")]
 public override string Name { get; set; }
}

我得承认,这例子是pretty做作...

I'll admit that that example is pretty contrived...

那些赞成使用,我可以拿出属性的最好的论据。我个人的看法是,在大多数情况下,之类的事情最好留给标记。

Those are the best arguments in favor of using the attribute that I can come up with. My personal opinion is that, for the most part, that sort of thing is best left to the markup.

这篇关于MVC 4数据注释&QUOT;显示&QUOT;属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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