I'm looking for some opinions on two different approaches to ViewModel definition
I have a Company class
public class Company
{
public string Name { get; set; }
public int CountryID { get; set; }
}
For the Create and Edit views I need a list of Countries to populate a DropDownList for CountryID selection. I can see two broad choices for how to structure the ViewModel that are detailed below.
Nested ViewModel
public class CompanyCreateEditViewModel
{
public Company Company { get; set; }
public IEnumerable<Country> Countries{ get; set; }
....
}
Flat ViewModel
public class CompanyCreateEditViewModel
{
public string Name { get; set; }
public int CountryID { get; set; }
public IEnumerable<Country> Countries{ get; set; }
....
}
At present I'm favoring the Nested approach as it saves me from defining fields for a second time, but I want to throw it open to better approaches and comments.
Thanks
I prefer nested, for several reasons:
IMHO, HTH.
I personally prefer the nested approach for presentation because it leads to a more logical design when you use partial views. You might have a
CompanyPartialView
used all across the application that knows how to render aCompany
, so it makes a lot of sense to expose theCompany
as a nested structure.On the other hand, flat ViewModel classes are the easiest to work with for data entry. You just have a bunch of form fields that all map to individual properties. So my strategy is usually to flatten them for data entry pages and nest them for presentation/report pages.