因为我们可以使用System.ComponentModel.DataAnnotations.DisplayAttribute为属性设置标签,所以我想对类使用它,但它不允许在类中使用。
using System.ComponentModel.DataAnnotations;
[Display(Name = "A person")]
public class Person
{
[Display(Name = "A name")]
public string Name { get; set; }
}有谁知道解决这个问题的办法吗?
编辑:我想在强类型视图上使用它。当我创建一个新的强类型视图时,类名是用HTML硬编码的,如下所示:
@model Models.Person
<fieldset>
<legend>Person</legend>
<div class="display-label">
@Html.LabelFor(model => model.Name)
</div>
</fieldset>我想做一些类似于Name属性的事情。
发布于 2012-07-03 05:08:08
DisplayName属性(来自System.ComponentModel)执行类似的功能,并且可以应用于类。
MSDN
发布于 2012-07-03 05:25:52
我真的不知道是否有另一种方法来做这件事,但我通常不会这样做,我会在视图中创建一个变量,然后我会在需要的地方调用hard code。在你的情况下,要做得更优雅一点,我会
@{
var viewName = typeof(Foo).Name;
}
@model Models.Person
<fieldset>
<legend>@viewName</legend>
<div class="display-label">
@Html.LabelFor(model => model.Name)
</div>
</fieldset>发布于 2017-03-10 23:43:20
使用装饰器模式,只需使用您自己的专门用于类的自定义属性包装DisplayAttribute。
using System;
using System.ComponentModel.DataAnnotations;
namespace YourNameSpaceHere.Support
{
[AttributeUsage(AttributeTargets.Class)]
public class DisplayForClassAttribute : Attribute
{
protected readonly DisplayAttribute Attribute;
public DisplayForClassAttribute()
{
this.Attribute = new DisplayAttribute();
}
public string ShortName
{
get { return this.Attribute.ShortName; }
set { this.Attribute.ShortName = value; }
}
public string Name
{
get { return this.Attribute.Name; }
set { this.Attribute.Name = value; }
}
public string Description
{
get { return this.Attribute.Description; }
set { this.Attribute.Description = value; }
}
public string Prompt
{
get { return this.Attribute.Prompt; }
set { this.Attribute.Prompt = value; }
}
public string GroupName
{
get { return this.Attribute.GroupName; }
set { this.Attribute.GroupName = value; }
}
public Type ResourceType
{
get { return this.Attribute.ResourceType; }
set { this.Attribute.ResourceType = value; }
}
public bool AutoGenerateField
{
get { return this.Attribute.AutoGenerateField; }
set { this.Attribute.AutoGenerateField = value; }
}
public bool AutoGenerateFilter
{
get { return this.Attribute.AutoGenerateFilter; }
set { this.Attribute.AutoGenerateFilter = value; }
}
public int Order
{
get { return this.Attribute.Order; }
set { this.Attribute.Order = value; }
}
public string GetShortName()
{
return this.Attribute.GetShortName();
}
public string GetName()
{
return this.Attribute.GetName();
}
public string GetDescription()
{
return this.Attribute.GetDescription();
}
public string GetPrompt()
{
return this.Attribute.GetPrompt();
}
public string GetGroupName()
{
return this.Attribute.GetGroupName();
}
public bool? GetAutoGenerateField()
{
return this.Attribute.GetAutoGenerateField();
}
public bool? GetAutoGenerateFilter()
{
return this.Attribute.GetAutoGenerateFilter();
}
public int? GetOrder()
{
return this.Attribute.GetOrder();
}
}
}用法如下:
[DisplayForClass(Name = "Approval Matrix")]
public class ApprovalMatrixViewModel
{
}https://stackoverflow.com/questions/11301107
复制相似问题