自定义 DataAnnotation 属性
当我在 ASP.NET MVC 3 模型中使用 DisplayAttribute 时,编写它们很快就会变得很痛苦,因为我们必须对字符串进行硬编码,或者从某个包含 const strings
的静态类中引用该字符串(这就是我现在已经有了,见下文)。但即使这样对我来说也太过分了。
我想提出一个名为 [SimpleDisplay] 的属性,它会通过查看
- 类名、
- 属性所附加的
属性名来隐式构造资源字符串。这可能吗?
像这样的东西
public class Product {
[SimpleDisplay] // it will take Product and Name and do something like this Product_Name
public string Name { get; set; }
}
如果可能的话,这就是我想要摆脱的东西:
[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;
}
现在我知道不可能继承 DisplayAttribute 因为它是密封的。我还有什么其他选择?这还有道理吗?
When I use DisplayAttribute in ASP.NET MVC 3 models it quickly becomes a pain writing them because we have to either hardcode the string or reference the string from a some static class that contains const strings
(which is what I have now, see below). But even that is too much for me.
I would like to come up with an attribute that would be called something like [SimpleDisplay] and it would implicitly construct the string for resources by looking at
- class name,
- property name that the attribute is attached to.
Is this possible?
Something like this
public class Product {
[SimpleDisplay] // it will take Product and Name and do something like this Product_Name
public string Name { get; set; }
}
This is what I want to get rid of, if possible:
[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;
}
Now I know that it is not possible to inherit the DisplayAttribute cause it's sealed. What other options I have? Does it even make sense?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会尝试仅创建一个标准属性和自定义 DataAnnotationsModelMetadataProvider。您可以重写 CreateMetadata 方法,该方法获取
IEnumerable
。您应该搜索您的属性并以您想要的任何方式填充模型元数据。
I would try creating just a standard attribute and custom DataAnnotationsModelMetadataProvider. You can override CreateMetadata method, which gets
IEnumerable<Attribute>
. You should than search for your attributeand populate model metadata in any way you want.
如果我正确理解您的意思,您可以创建一个简单的自定义属性,如下所示:
然后您可以将其用作您的属性的属性。 MVC HTML 扩展将获取您的自定义属性。
If i have a correct understanding what you mean, you may just create a simple custom attribute like this one:
You may then use it as an attribute on your properies. MVC HTML extensions will pickup your custom attribute.