Steve Michelotti

C#, ASP.NET, and other stuff

  Home  |   Contact  |   Syndication    |   Login
  108 Posts | 1 Stories | 410 Comments | 51 Trackbacks

News

View Steve Michelotti's profile on LinkedIn






Google My Blog

What I'm Reading:

Shelfari: Book reviews on your book blog

Tag Cloud


Archives

Post Categories

Image Galleries

Blogs

Code

Publications

Since MVC has been released I have observed much confusion about how best to construct view models. Sometimes this confusion is not without good reason since there does not seem to be a ton of information out there on best practice recommendations.  Additionally, there is not a “one size fits all” solution that acts as the silver bullet. In this post, I’ll describe a few of the main patterns that have emerged and the pros/cons of each. It is important to note that many of these patterns have emerged from people solving real-world issues.

Another key point to recognize is that the question of how best to construct view models is *not* unique to the MVC framework.  The fact is that even in traditional ASP.NET web forms you have the same issues.  The difference is that historically developers haven’t always dealt with it directly in web forms – instead what often happens is that the code-behind files end up as monolithic dumping grounds for code that has no separation of concerns whatsoever and is wiring up view models, performing presentation logic, performing business logic, data access code, and who knows what else.  MVC at least facilitates the developer taking a closer look at how to more elegantly implement Separation of Concerns.

Pattern 1 – Domain model object used directly as the view model

Consider a domain model that looks like this:

   1:  public class Motorcycle
   2:  {
   3:      public string Make { get; set; }
   4:      public string Model { get; set; }
   5:      public int Year { get; set; }
   6:      public string VIN { get; set; }
   7:  }

When we pass this into the view, it of course allows us to write simple HTML helpers in the style of our choosing:

   1:  <%=Html.TextBox("Make") %>
   2:  <%=Html.TextBoxFor(m => m.Make) %>

And of course with default model binding we are able to pass that back to the controller when the form is posted:

   1:  public ActionResult Save(Motorcycle motorcycle)

While this first pattern is simple and clean and elegant, it breaks down fairly quickly for anything but the most trivial views. We are binding directly to our domain model in this instance – this often is not sufficient for fully displaying a view.

Pattern 2 – Dedicated view model that *contains* the domain model object

Staying with the Motorcycle example above, a much more real-world example is that our view needs more than just a Motorcycle object to display properly.  For example, the Make and Model will probably be populated from drop down lists. Therefore, a common pattern is to introduce a view model that acts as a container for all objects that our view requires in order to render properly:

   1:  public class MotorcycleViewModel
   2:  {
   3:      public Motorcycle Motorcycle { get; set; }
   4:      public SelectList MakeList { get; set; }
   5:      public SelectList ModelList { get; set; }
   6:  }

In this instance, the controller is typically responsible for making sure MotorcycleViewModel is correctly populated from the appropriate data in the repositories (e.g., getting the Motorcycle from the database, getting the collections of Makes/Models from the database).  Our Html Helpers change slightly because they refer to Motorcycle.Make rather than Make directly:

   1:  <%=Html.DropDownListFor(m => m.Motorcycle.Make, Model.MakeList) %>

When the form is posted, we are still able to have a strongly-typed Save() method:

   1:  public ActionResult Save([Bind(Prefix = "Motorcycle")]Motorcycle motorcycle)

Note that in this instance we had to use the Bind attribute designating “Motorcycle” as the prefix to the HTML elements we were interested in (i.e., the ones that made up the Motorcycle object).

This pattern is simple and elegant and appropriate in many situations. However, as views become more complicated, it also starts to break down since there is often an impedance mismatch between domain model objects and view model objects.

 

Pattern 3 – Dedicated view model that contains a custom view model entity

As views get more complicated it is often difficult to keep the domain model object in sync with concerns of the views.  In keeping with the example above, suppose we had requirements where we need to present the user a checkbox at the end of the screen if they want to add another motorcycle.  When the form is posted, the controller needs to make a determination based on this value to determine which view to show next. The last thing we want to do is to add this property to our domain model since this is strictly a presentation concern. Instead we can create a custom “view model entity” instead of passing the actual Motorcycle domain model object into the view. We’ll call it MotorcycleData:

   1:  public class MotorcycleData
   2:  {
   3:      public string Make { get; set; }
   4:      public string Model { get; set; }
   5:      public int Year { get; set; }
   6:      public string VIN { get; set; }
   7:      public bool AddAdditionalCycle { get; set; }
   8:  }

This pattern requires more work and it also requires a “mapping” translation layer to map back and forth between the Motorcycle and MotorcycleData objects but it is often well worth the effort as views get more complex.  This pattern is strongly advocated by the authors of MVC in Action (a book a highly recommend).  These ideas are further expanded in a post by Jimmy Bogard (one of the co-authors) in his post How we do MVC – View Models. I strongly recommended reading Bogard’s post (there are many interesting comments on that post as well). In it he discusses approaches to handling this pattern including using MVC Action filters and AutoMapper (I also recommend checking out AutoMapper).

Let’s continue to build out this pattern without the use of Action filters as an alternative. In real-world scenarios, these view models can get complex fast.  Not only do we need to map the data from Motorcycle to MotorcycleData, but we also might have numerous collections that need to be populated for dropdown lists, etc.  If we put all of this code in the controller, then the controller will quickly end up with a lot of code dedicated just to building the view model which is not desirable as we want to keep our controllers thin. Therefore, we can introduce a “builder” class that is concerned with building the view model.

   1:  public class MotorcycleViewModelBuilder
   2:  {
   3:      private IMotorcycleRepository motorcycleRepository;
   4:   
   5:      public MotorcycleViewModelBuilder(IMotorcycleRepository repository)
   6:      {
   7:          this.motorcycleRepository = repository;
   8:      }
   9:   
  10:      public MotorcycleViewModel Build()
  11:      {
  12:          // code here to fully build the view model 
  13:          // with methods in the repository
  14:      }
  15:  }

This allows our controller code to look something like this:

   1:  public ActionResult Edit(int id)
   2:  {
   3:      var viewModelBuilder = new MotorcycleViewModelBuilder(this.motorcycleRepository);
   4:      var motorcycleViewModel = viewModelBuilder.Build();
   5:      return this.View();
   6:  }

Our views can look pretty much the same as pattern #2 but now we have the comfort of knowing that we’re only passing in the data to the view that we need – no more, no less.  When the form is posted back, our controller’s Save() method can now look something like this:

   1:  public ActionResult Save([Bind(Prefix = "Motorcycle")]MotorcycleData motorcycleData)
   2:  {
   3:      var mapper = new MotorcycleMapper(motorcycleData);
   4:      Motorcycle motorcycle = mapper.Map();
   5:      this.motorcycleRepository.Save(motorcycle);
   6:      return this.RedirectToAction("Index");
   7:  }

Conceptually, this implementation is very similar to Bogard’s post but without the AutoMap attribute.  The AutoMap attribute allows us to keep some of this code out of the controller which can be quite nice.  One advantage to not using it is that the code inside the controller class is more obvious and explicit.  Additionally, our builder and mapper classes might need to build the objects from multiple sources and repositories. Internally in our mapper classes, you can still make great use of tools like AutoMapper.

In many complex real-world cases, some variation of pattern #3 is the best choice as it affords the most flexibility to the developer.

 

Considerations

How do you determine the best approach to take?  Here are some considerations to keep in mind:

Code Re-use – Certainly patterns #1 and #2 lend themselves best to code re-use as you are binding your views directly to your domain model objects. This leads to increased code brevity as mapping layers are not required. However, if your view concerns differ from your domain model (which they often will) options #1 and #2 begin to break down.

Impedance mismatch – Often there is an impedance mismatch between your domain model and the concerns of your view.  In these cases, option #3 gives the most flexibility.

Mapping Layer – If custom view entities are used as in option #3, you must ensure you establish a pattern for a mapping layer. Although this means more code that must be written, it gives the most flexibility and there are libraries available such as AutoMapper that make this easier to implement.

Validation – Although there are many ways to perform validation, one of the most common is to use libraries like Data Annotations. Although typical validations (e.g., required fields, etc.) will probably be the same between your domain models and your views, not all validation will always match.  Additionally, you may not always be in control of your domain models (e.g., in some enterprises the domain models are exposed via services that UI developers simply consume).  So there is a limit to how you can associate validations with those classes.  Yes, you can use a separate “meta data” class to designate validations but this duplicates some code similar to how a view model entity from option #3 would anyway. Therefore, option #3 gives you the absolute most control over UI validation.

 

Conclusion

The following has been a summary of several of the patterns that have emerged in dealing with view models. Although these have all been in the context of ASP.NET MVC, the problem with how best to deal with view models is also an issue with other frameworks like web forms as well. If you are able to bind directly to domain model in simple cases, that is the simplest and easiest solution. However, as your complexity grows, having distinct view models gives you the most overall flexibility.

posted on Sunday, October 25, 2009 9:03 AM

Feedback

# re: ASP.NET MVC View Model Patterns 10/25/2009 12:21 PM Lance
Great post/insight. Keep up the good work

# re: ASP.NET MVC View Model Patterns 10/26/2009 12:43 PM Usman Bashir
Yup I too prefer the third option and we successfully deployed in commercial grade application (although more code and effort came but at the end it benefited us)

# re: ASP.NET MVC View Model Patterns 10/26/2009 12:52 PM D. Lambert
Have you seen any of Rocky Lhotka's work with CLSA for MVVM? ex:

http://www.lhotka.net/weblog/CSLANET38Beta2MVVMSupport.aspx

This is brand-new, and I haven't played with it much, but I'm hopeful that this will be a good combination of the approaches you listed.

# Combine Approaches 10/26/2009 1:30 PM Dominic Pettifer
Is it recommended to combine all three approaches in the same MVC application do you think? Maybe you have a simple User Details page and the displayed fields are pretty much the same on your 'User' entity, whereas another part of the app needs to display a sort of flattened view of several domain entities.

I've been trying to use approach 3 exclusively, but it is a lot of code to write, and sometimes the View models seem almost identical to the Domain models. I've been getting my Controller Actions to call a sort of 'Service' layer which 'fills-in' my view models, maybe I should try this mapping layer approach with AutoMapper.

# re: ASP.NET MVC View Model Patterns 10/26/2009 1:44 PM Geoffrey Braaf
Obviously when building a site you think about these things and somewhat unconsciously decide for one or the other. In my most recent projects I've always chosen for option #3 in combination with Automapper. True, it makes for more code, but I believe it promotes readability. Who wants to wade through objects with many members you don't need but are there so you can reuse the objects. I still prefer code that's easily understood and read even if I trade in on 'compactness' of the code-base and reduce the ability to reuse the (generally small) view specific model objects.

# re: ASP.NET MVC View Model Patterns 10/26/2009 1:50 PM Joseph Daigle
I prefer a combination of #2 and #3. I always use dedicated view model objects, but usually if the model is simple enough, I'll add in the domain model object via composition. Even if I don't include the domain model itself, I still have the flexibility to change the view model however I need.

# re: ASP.NET MVC View Model Patterns 10/26/2009 2:14 PM Steve
@D. Lambert - I haven't seen Lhotka's work for MVVM yet but I'll definitely check it out.

@Dominic Pettifer - This is not an easily answered question. At the end of the day, you have to make a pragmatic decision for what you think is best for your application. Some people do combine these approaches in a single application if the domain model is simple on most of the screens and only complex (with a lot of view model impedance mismatch) on a few. However, other people (as you can see from some of the comments just on this post) opt to stick only with option #3 for consistency.

# re: ASP.NET MVC View Model Patterns 10/27/2009 7:11 AM Raghuraman
Steve,

Thanks for another great post !!! ViewModel patterns are explained in a simple language.

Quick question : Isn't ViewModel as Single word ? or is this MVC View Model different from the M-V-VM pattern ?


# re: ASP.NET MVC View Model Patterns 10/27/2009 11:40 AM Steve
@Raghu - In the context of a "discussion" people typically use "view model" as two words but as a "noun" then a lot of times you'll see it as one word. :)

Conceptually, as a pattern, this has similar concepts to M-V-VM but often the specifics of M-V-VM get put in the context of Silverlight and WPF (e.g., http://msdn.microsoft.com/en-us/magazine/dd419663.aspx). But at the end of the day, it all comes back to conceptual patterns.

# re: ASP.NET MVC View Model Patterns 10/27/2009 6:48 PM Raghuraman
Thanks for your clarification.

Regards

Raghuraman

# re: ASP.NET MVC View Model Patterns 10/29/2009 2:43 PM Bangoker
Wouldnt the edit method need to use the Id somewhere?



1: public ActionResult Edit(int id) //YOU GET ID HERE

2: {

3: var viewModelBuilder = new MotorcycleViewModelBuilder(this.motorcycleRepository);

4: var motorcycleViewModel = viewModelBuilder.Build(); //SHOULDNT YOU USE ID HERE?

5: return this.View();

6: }



# re: ASP.NET MVC View Model Patterns 10/29/2009 2:51 PM Steve
@Bangoker - Yes, it absolutely could. The id would be passed into the MotorcycleViewModelBuilder so that it can get the correct motorcycle object. The repository is passed in because the builder might need to populate a whole bunch of collections for dropdowns. In fact, if this screen were loading for the first time, you wouldn't need the id at all (and then it wouldn't be in the method signature). The example in my code was a slight "blog post oversight." :)

# re: ASP.NET MVC View Model Patterns 11/4/2009 2:40 AM Thanigainathan
Fantastic article sir. Will be of more use. Anyways if I were to use the Service layer, in that case method #3 will be useful according to you .But I have to rewrite all my code again like I have to create custom view model . How will this be beneficial compared to webforms ?

Thanks,
Thani

# re: ASP.NET MVC View Model Patterns 11/4/2009 9:13 PM Steve
@Thanigainathan - You don't have to re-write *all* your code. If you go #3, it's because you're view model does not match your domain model in the first place. In that case, you'll *want* to write code for your view model because your domain model isn't a good fit for the view.

The same would be true for web forms. In web forms, what objects are you binding your aspx pages too? If you bind them directly to your domain objects and the concerns of your view does not match the concerns of your domain objects, you're code will not be very elegant. Thus, you could apply the same concepts to web forms with a "mapping" layer that translates between your view models and domain models.

# re: ASP.NET MVC View Model Patterns 11/5/2009 12:31 AM andrewjboyd
On the subject of the edit method, wouldn't it be something like this: (to prevent uncontrollable exceptions if the user was trying to hack the id, ie they change it to abc or something, you don't want some ugly error screen)

1: public ActionResult Edit(int? id)
2: {
3: if (id != null)
4: {
5: var viewModelBuilder = new MotorcycleViewModelBuilder(this.motorcycleRepository);
6: var motorcycleViewModel = viewModelBuilder.Build(id.Value);
7: return this.View(motorcycleViewModel);
8: }
9: else
10: {
11: return this.View("Error"...);
12: }
13: }

# re: ASP.NET MVC View Model Patterns 11/5/2009 9:02 PM ankur
can any one please share the source code for this.

# re: ASP.NET MVC View Model Patterns 11/6/2009 11:06 PM Steve
I've used all 3 personally, depending on the complexity of the page.

pattern 2 is my most widely used one, although #3 is more acceptable, especially in an enterprise solution.

Lastly, I'd say the best solution for testing is where I would focus as well - it would allow an easy to mock solution for testing the UI pieces.

# re: ASP.NET MVC View Model Patterns 11/7/2009 11:16 AM James Fleming
I was at the code camp and heard you speak. Thank God you ran out of time - if you went on any longer, I think my head would explode! Looking forward to pulling apart your project. I've been doing MVC for 9 months, and it's clear there's much I still need to learn. A great presentation!

# re: ASP.NET MVC View Model Patterns 11/7/2009 8:24 PM Steve
@andrewjboyd - regarding the Edit method, if the id was required, I wouldn't handle the absence of it with an if/then statement this that is an exceptional case. Instead of would use the [HandleError] attribute (or if you've defined a custom one) which appropriate redirects to your error display so you don't have to clutter all of your controller action methods with it.

@ankur - this post was meant to display the general patterns and the code samples corresponding to each one. there is not a full zip download specific to just this post.

@James Fleming - thanks for the kind words. the code samples for my presentation are now available for download.

# Pattern 4 – Smarter Views 11/9/2009 8:59 AM James Fleming
Another possible pattern for the ViewModel problem is to make the View more responsible for itself. Basically, the Controller handles the domain object & the views pull JSON data for dropdown list boxes as the view requires. Each of my controllers offer up a JSON method for pulling domain data for a dropdown. I use JQuery/Ajax on the View to pull it all together. Any thoughts on this approach?

# re: ASP.NET MVC View Model Patterns 11/10/2009 9:53 PM Steve
@James Fleming - Certainly with the increase in AJAX, more knowledge has to be pushed to the view. Typically, the JSON approach is more relevant to drop downs, etc. (which you pointed out) but not typically as much with the entity view model (though it will be interesting to see how much client side templates influences this). Either way, it seems to primary view models will still live in C# management by the controller and JSON will be used for populating values for other controls such as listboxes, dropdowns, etc.

# re: ASP.NET MVC View Model Patterns 11/16/2009 4:45 PM sarmaad
good one Steve. thanks for the clarification.

I always used #3 pattern, but the thought process on deciding which approach to take is a time consuming one :) this is what i find anyway.

usually projects start small then they buildup to be come a monster. having started with the right approach it certainly make it easier.

sarmaad

# re: ASP.NET MVC View Model Patterns 11/16/2009 6:14 PM Jay
I am trying to understand where a service (validation) layer fits in. In order to decouple data access from controller, we use separate repositories. Then we use a wrapper class with IValidationDictionary to decouple service from controller. So the data flow goes EF->Repository-> Service->Wrapper class ->Controller->View. Where the view model fits in this scenario? Can the Service provide view model objects along with validation? Or do we need to add separate View Model class depending on the Service? If so, do we accept the tight coupling between View Model and service or View Model and Controller?

# re: ASP.NET MVC View Model Patterns 11/17/2009 4:38 AM Omu
Automapper was not intended to be used for this kind of stuff

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: