Reputation: 317
I'm quite new to ASP MVC so when I first created a page I made a ViewModel that has flattened properties related to Address and Contact information. These properties are very common and I can see them being reused. So let's say I have the view model below:
public class InformationViewModel {
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
public string Phone { get; set; }
public string EMail { get; set; }
public Uri WebSiteURL { get; set; }
public Uri FacebookURL { get; set; }
[HiddenInput(DisplayValue = false)]
public string AddressId { get; set; }
public string AttentionLine { get; set; }
public string CareOf { get; set; }
public string CountryCode { get; set; }
public string CountryName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public Dictionary<string, string> Countries { get; set; }
public Dictionary<string, string> States { get; set; }
public string StateCode { get; set; }
public string StateName { get; set; }
public string PostalCode { get; set; }
//Some other properties specific to the view here
}
The first two blocks of properties are reusable across multiple view models. Now I'm working on a new page that requires these same properties.
1) Would I separate them out into their own View Model (or Model?) files (e.g. AddressViewModel/ContactViewModel)?
1a) If I do separate them out and reuse them by including them as a property in InformationViewModel
would that be with the line: public AddressViewModel addressViewModel {get; set;}
?
2) How would I remove or apply data annotations in an included view model (e.g. public AddressViewModel addressViewModel {get; set;}
? For example, if I want Name to be required on some Views but not for others.
Upvotes: 1
Views: 270
Reputation: 218732
View models are specific to views. So it is a good idea to create view specific flat view models. But if you have some common attributes in more than one view models, you may inherit from a base view model as needed.
public class CreateUser
{
[Required]
public string Name {set;get;}
[Required]
public string Email {set;get;}
public virtual string City { set; get; }
}
public class CreateUserWithAddress : CreateUser
{
[Required]
public string AddressLine1 {set;get;}
public string AddressLine12 {set;get;}
[Required]
public override string City { set; get; } // make city required
}
When inhering from a base view model, you should be able to override a property of base class and add a data annotation to that in your child class (Like we did with City
property). But you cannot remove the data annotation defined in the base class inside your derived class.
Upvotes: 2