views:

193

answers:

4

How do most developers handle Typed Views in ASP.NET MVC when dealing with large applications? We are considering putting View-specific models in the Models folder, then putting all domain objects into a separate project. This way our Controllers can easily add the domain object to the typed view, without the domain object needing to be aware of the View layout itself.

For example, if we have an Employee object with:

  • Id
  • First Name
  • Last Name
  • Status

Then our Employee View might use a ViewEmployeeModel object with:

  • Employee object
  • List to populate Status drop-down
  • etc

Is this a sensible approach? Are there better ways to accomplish the same thing? It seems a little strange since I'd basically have two models (one for the view, one for the business objects), but isn't it better than using untyped views?

+1  A: 

I think this is a pretty sensible approach. One thing that might help you out is AutoMapper.

mgroves
+7  A: 

I do this almost as a rule, because:

  1. It lets you design the app view-first instead of DB-first, which is nice when working with customer representatives.
  2. Views typically have a much "flatter" object graph than, say, Entity Framework models. LINQ makes it easy to map these.
  3. The views and the data model can evolve much more independently.
  4. It's typically easier to model bind to a flat view model with, say, FK IDs than an entity model which expects fully materialized related objects.
  5. You don't have to worry about accidentally exposing "secret" properties or whitelisting properties for updates.
Craig Stuntz
Great way to think about it, thanks!
Jess
+1  A: 

Seems fine, you have the advantage that the model only contains information needed by the view and not lots of pesky business logic functions / values.

DeletedAccount
+2  A: 

Don't have the reputation to comment, but Craig is right. It's a variation of the Model-View-ViewModel pattern. There's a good article on it available at Los Techies.

The article also uses the AutoMapper code that mgroves pointed out so you should be able to kill two birds with one stone.

andymeadows