In my MVC application, I defined the DataAnnotations in the domain models. Although the DataAnnotations properties as Display, etc. can be retrieved when using Domain model, they cannot be retrieved when using the same properties on ViewModel and using this ViewModel. I think it is not seem to good to define the DataAnnotations in ViewModel again. So, is it possible or which way should I follow?
Domain Model:
public class Issue
{
[Key]
public int ID { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Project Number")]
public int ProjectID { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Issue Definition")]
public string Description { get; set; }
//... removed for brevity
//Navigation Properties:
public virtual ICollection<FileAttachment> FileAttachments { get; set; }
}
ViewModel:
public class IssueViewModel
{
public int ID { get; set; }
public int ProjectID { get; set; }
public string Description { get; set; }
//... removed for brevity
//Navigation Properties:
public virtual ICollection<FileAttachment> FileAttachments { get; set; }
}
You can create a new buddy class which holds all metadata about properties and class.
Then, we must tell the MVC Framework about the buddy class through the
MetadataType
attribute, which takes the type of the buddy class as its argument. Buddy classes must be defined in the same namespace and must also bepartial
classes.Additional note:
If
IssueMetadata
andIssue
(orIssueViewModel
) classes located in different assemblies, then you can associate classes with their buddy class in runtime, like that:And, just call this static method in
global.asax
: