我可以添加MVC 2 DataAnnotation属性,以现有的属性? [英] Can I add MVC 2 DataAnnotation attributes to existing properties?

查看:88
本文介绍了我可以添加MVC 2 DataAnnotation属性,以现有的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是生成的类作为一个模型,我想补充DataAnnotation属性它的一些属性。因为它是一个生成的code,我不想直接添加注释。有另一种方式将其连接到一个属性?

I'm using a generated class as a model, and I wish to add DataAnnotation attributes to some of its properties. As it's a generated code, I don't want to add the annotations directly. Is there another way to attach them to a property?

我会考虑做模型的接口,并使用部分类来获取生成的类来订阅它。有一个不太复杂的解决方案,假设即使将工作?

I'd considered making the model an interface, and using a partial class to get the generated class to subscribe to it. Is there a less elaborate solution, assuming that would even work?

推荐答案

是的,有。你必须创建元数据类,将有相同的属性,你的原始模型,并将其与MetadataType属性连接到你的模型:

Yes there is. You have to create metadata class that will have the same properties that your original model, and connect it to your model with MetadataType attribute:

[MetadataType(typeof(MyModelMetadata))]
public partial class OriginalMyModel
{
}

public class MyModelMetadata
{
    [Required]
    public string MyProperty;  

    // ...
}

在这个例子ebove OriginalModel是您正确的模型类,MyModelMetadata只对注释的属性使用的类。 MyModelMetadata应该有你的模型具有相同的属性。

In the example ebove OriginalModel is your proper model class, and MyModelMetadata is a class used only for annotating properties. MyModelMetadata should have the same properties that your model has.

这篇关于我可以添加MVC 2 DataAnnotation属性,以现有的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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