views:

302

answers:

2

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

+5  A: 

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 a Company, so it makes a lot of sense to expose the Company 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.

Aaronaught
Completely agree. I use nested for presentation - `CompanyViewModel` - and flat for data entry - `CompanyCreateEditViewModel`.
Jarrett Meyer
+1  A: 

Hello,

I prefer nested, for several reasons:

  • That's what object oriented is all about.
  • If you use LINQ to SQL or Entities, or an ORM, you can simply pass the ORM objects and not have to pass all kinds of properties.
  • You can pass other views, so you can create separate models for partial views, and if that view uses a partial, you can pass the partial view model class as a property of the view model class.

IMHO, HTH.

Brian