Can I add MVC 2 DataAnnotation attributes to existing properties?

旧城冷巷雨未停 提交于 2019-12-06 03:14:48

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;  

    // ...
}

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.

You can use the MetadataType attribute on your class:

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute.aspx

In practice, I've seen the metadata get out of sync with a generated model pretty frequently, though, which can lead to some headaches. You may want to look into an alternate validation mechanism instead of data annotations.

I've been using Fluent Validation, which is very easy to pick up and start using. There is even a Fluent Validation to xVal integration piece in Fluent Validation 2.0 (still in beta) that you can bring into your project for client-side validation.

Fluent Validation allows you to define your validation in a separate class. All you would need to do is add an attribute to your generated class telling it what validator to use, which could be accomplished through partial classes.

Alternatively, you could create view-specific models that are mapped to from your domain model that contain your data annotations. In that case, simplify the back-and-forth mapping using something like AutoMapper. Then, if your domain model changes, you get compile-time errors versus the metadata approach.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!