【发布时间】:2013-02-19 15:56:31
【问题描述】:
我有不同的人应该以不同的名称看到的字段。
例如,假设我有以下用户类型:
public enum UserType {Expert, Normal, Guest}
我实现了一个IMetadataAware 属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class DisplayForUserTypeAttribute : Attribute, IMetadataAware
{
private readonly UserType _userType;
public DisplayForUserTypeAttribute(UserType userType)
{
_userType = userType;
}
public string Name { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
if (CurrentContext.UserType != _userType)
return;
metadata.DisplayName = Name;
}
}
我的想法是我可以根据需要覆盖其他值,但当我不这样做时,可以使用默认值。例如:
public class Model
{
[Display(Name = "Age")]
[DisplayForUserType(UserType.Guest, Name = "Age (in years, round down)")]
public string Age { get; set; }
[Display(Name = "Address")]
[DisplayForUserType(UserType.Expert, Name = "ADR")]
[DisplayForUserType(UserType.Normal, Name = "The Address")]
[DisplayForUserType(UserType.Guest, Name = "This is an Address")]
public string Address { get; set; }
}
问题是当我有多个相同类型的属性时,DataAnnotationsModelMetadataProvider 只为第一个运行OnMetadataCreated。
在上面的示例中,Address 只能显示为“地址”或“ADR”——其他属性永远不会执行。
如果我尝试使用不同的属性 - DisplayForUserType、DisplayForUserType2、DisplayForUserType3,一切都会按预期工作。
我在这里做错了吗?
【问题讨论】:
标签: c# asp.net-mvc-3 data-annotations modelmetadata