Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a View Model + Data Model in ASP.NET MVC to support typed views?

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?

like image 704
Beep beep Avatar asked Dec 09 '22 20:12

Beep beep


2 Answers

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.
like image 136
Craig Stuntz Avatar answered May 20 '23 18:05

Craig Stuntz


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.

like image 40
andymeadows Avatar answered May 20 '23 16:05

andymeadows