Thursday, January 12, 2012

How to validate Model Data using Data Annotations Attributes but you don’t want to change Model layer?

How to validate Model Data using Data Annotations Attributes but you don’t want to change Model layer?


In MVC, you could use Data Annotations Attributes to validate Model Data. Reference:




But what if model layer is from another layer, you don’t want to change anything on that class?

Solution: MetadataTypeAttribute


Steps:

1.      Create a class inherent the class from Another layer

2.      Add MetadataTypeAttribute to point to another class 
3.   Add Data Annotation into second class

Code example:

    public class ValidationExtension
    {
             [Required(ErrorMessage = "Title is required.")]
       public string Title;
    }


    [MetadataType(typeof(ValidationExtension))]
    public class MVCModelLayerClass: BusinessLayerClass
      {

    }








No comments:

Post a Comment