自定义DataAnnotation属性

mar*_*are 2 c# asp.net-mvc data-annotations asp.net-mvc-3

当我在ASP.NET MVC 3模型中使用DisplayAttribute时,它很快就会变得很难写,因为我们必须对字符串进行硬编码或从包含的某个静态类引用字符串const strings(这就是我现在所见,见下文).但即使这对我来说太过分了.

我想提出一个类似于[SimpleDisplay]的属性,它会通过查看隐式构造资源的字符串

  1. 班级名称,
  2. 属性附加到的属性名称.

这可能吗?

像这样的东西

public class Product {

 [SimpleDisplay] // it will take Product and Name and do something like this Product_Name
 public string Name { get; set; } 

}
Run Code Online (Sandbox Code Playgroud)

这是我想要摆脱的,如果可能的话:

    [Display(ResourceType = typeof(Resources.Localize), Name = ResourceStrings.product_prettyid)]
    public virtual int PrettyId
    {
        get;
        set;
    }

    [Display(ResourceType = typeof(Resources.Localize), Name = ResourceStrings.product_name)]
    public virtual string Title
    {
        get;
        set;
    }
Run Code Online (Sandbox Code Playgroud)

现在我知道继承DisplayAttribute是不可能的,因为它是密封的.我还有其他选择吗?它甚至有意义吗?

Jak*_*cki 5

我会尝试只创建一个标准属性和自定义DataAnnotationsModelMetadataProvider.您可以覆盖获取的CreateMetadata方法IEnumerable<Attribute>.您应该搜索您的属性

attributes.OfType<SimpleDisplayAttribute>().FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

并以您想要的任何方式填充模型元数据.