Posts
203
Comments
1116
Trackbacks
51
ASP.NET MVC View Model Patterns

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 Print
Comments
Gravatar
# re: ASP.NET MVC View Model Patterns
Lance
10/25/2009 12:21 PM
Great post/insight. Keep up the good work
Gravatar
# re: ASP.NET MVC View Model Patterns
Usman Bashir
10/26/2009 12:43 PM
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)
Gravatar
# re: ASP.NET MVC View Model Patterns
D. Lambert
10/26/2009 12:52 PM
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.
Gravatar
# Combine Approaches
Dominic Pettifer
10/26/2009 1:30 PM
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.
Gravatar
# re: ASP.NET MVC View Model Patterns
Geoffrey Braaf
10/26/2009 1:44 PM
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.
Gravatar
# re: ASP.NET MVC View Model Patterns
Joseph Daigle
10/26/2009 1:50 PM
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.
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
10/26/2009 2:14 PM
@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.
Gravatar
# re: ASP.NET MVC View Model Patterns
Raghuraman
10/27/2009 7:11 AM
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 ?
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
10/27/2009 11:40 AM
@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.
Gravatar
# re: ASP.NET MVC View Model Patterns
Raghuraman
10/27/2009 6:48 PM
Thanks for your clarification.

Regards

Raghuraman
Gravatar
# re: ASP.NET MVC View Model Patterns
Bangoker
10/29/2009 2:43 PM
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: }

Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
10/29/2009 2:51 PM
@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." :)
Gravatar
# re: ASP.NET MVC View Model Patterns
Thanigainathan
11/4/2009 2:40 AM
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
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
11/4/2009 9:13 PM
@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.
Gravatar
# re: ASP.NET MVC View Model Patterns
andrewjboyd
11/5/2009 12:31 AM
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: }
Gravatar
# re: ASP.NET MVC View Model Patterns
ankur
11/5/2009 9:02 PM
can any one please share the source code for this.
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
11/6/2009 11:06 PM
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.
Gravatar
# re: ASP.NET MVC View Model Patterns
James Fleming
11/7/2009 11:16 AM
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!
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
11/7/2009 8:24 PM
@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.
Gravatar
# Pattern 4 – Smarter Views
James Fleming
11/9/2009 8:59 AM
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?
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
11/10/2009 9:53 PM
@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.
Gravatar
# re: ASP.NET MVC View Model Patterns
sarmaad
11/16/2009 4:45 PM
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
Gravatar
# re: ASP.NET MVC View Model Patterns
Jay
11/16/2009 6:14 PM
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?
Gravatar
# re: ASP.NET MVC View Model Patterns
Omu
11/17/2009 4:38 AM
Automapper was not intended to be used for this kind of stuff
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
11/22/2009 7:22 AM
@Jay - Interesting question. In general, I would say that given your two choices at the end, the better approach would be to couple the view model and the controller. The view models are intended to be used only by your web layer with their only concern to be assisting your view/presentation layer. View models are not intended to bleed out to repositories.
Gravatar
# re: ASP.NET MVC View Model Patterns
C.T.
11/24/2009 11:51 AM
thanks, I got some ideas from this post, I think maybe there is an easier and more clear solution to do this. some times the complexity is just made by ourselves.
Gravatar
# re: ASP.NET MVC View Model Patterns
C.T.
11/25/2009 12:38 AM
i found this pattern.

http://stackoverflow.com/questions/768236/how-to-create-a-strongly-typed-master-page-using-a-base-controller-in-asp-net-mvc/1794863#1794863
Gravatar
# re: ASP.NET MVC View Model Patterns
sparky
1/26/2010 3:53 PM
What would the optimal directory structure be for this (for the model)?
Gravatar
# re: ASP.NET MVC View Model Patterns
Andy
4/19/2010 4:51 PM
Really nice article. I was confused about viewmodels before. Not any more.
Gravatar
# re: ASP.NET MVC View Model Patterns
Graeme
4/26/2010 5:47 PM
This is why I love MVC, there are so many out there willing to share their knowledge. Great post, cleared up a number of my questions in a matter of minutes!
Gravatar
# re: ASP.NET MVC View Model Patterns
Andrew Duffy
5/12/2010 11:44 PM
Great article, I was looking at the default AccountModels.cs that comes in MVC2 and thinking what's going on here?
Gravatar
# re: ASP.NET MVC View Model Patterns
NEE
6/12/2010 1:52 PM
First, i just want to know what's the difference between the “view model entity” and DTO?

Second, should i use the view model below to avoid creating a new “view model entity”?

public class MotorcycleViewModel
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public string VIN { get; set; }
public bool AddAdditionalCycle { get; set; }

public SelectList MakeList { get; set; }
public SelectList ModelList { get; set; }
}
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
6/13/2010 10:38 PM
@NEE - The view model entity is somewhat of a similar concept to the DTO - they're both essentially just containers of state. The primary difference between them is that the view model has *presentation concerns" in the form of model metadata (e.g., validation attributes, UIHints, UI DisplayNames, etc.) where as DTO is typically just to transport data.

The MotorcycleViewModel class you have above is certainly one of the accepted ways to create a view model and is a fine choice as well.
Gravatar
# re: ASP.NET MVC View Model Patterns
Wilton
7/21/2010 6:18 PM


1: public ActionResult Edit(int id)

2: {

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

4: var motorcycleViewModel = viewModelBuilder.Build();

5: return this.View(motorcycleViewModel); // <---

6: }

How are you passing the view model in? Don't you need to include it like I put above? Or are you someplace else? Wouldn't you need this information to populate the existing form on the page?

Gravatar
# re: ASP.NET MVC View Model Patterns
Lee
8/25/2010 8:56 AM
I am fairly new to the MVC framework and the Pattern 3 is one which architecturally sits most comfortably with me. One question I have though is - what is your unit testing strategy for controller methods which use a 'view model builder' assuming you treat them as dependencies of course.
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
8/26/2010 1:59 PM
@Lee - I don't inject the view model builder. The dependencies I inject are things that are going across boundaries (e.g., calls to database, web server, email, etc., etc.). So when I test controllers, I'd inject those repositories, etc. and the view model builder would be executed in the context of the controller test.
Gravatar
# re: ASP.NET MVC View Model Patterns
Paiman Roointan
9/23/2010 11:18 AM
hi. check my post of asp.net MVC cons and pros.

http://sepidweb.ir/englishblog/post/2010/09/07/ASPNET-MVC-cons-and-pros.aspx
Gravatar
# re: ASP.NET MVC View Model Patterns
Degrees
10/8/2010 1:44 PM
Its going to take me a bit longer to figure out MVC but thanks for the info on constructing view models.
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve Peters
10/27/2010 8:24 PM
Thats the problem with most things microsoft nowadays. There are too many ways do things and no guidance. It would have been better if MS had somehow "locked" the MVC system so that things could "only be done one kind of way".
Gravatar
# re: ASP.NET MVC View Model Patterns
Justin Holzer
1/28/2011 4:05 PM
I'm not sure why some people think there has to be a single be-all-end-all design pattern. Each of the 3 patterns listed are perfectly acceptable, but which one you choose should depend on each particular view and what data needs to go in to (from the controller) and out of (from the form post) the view.
Gravatar
# re: ASP.NET MVC View Model Patterns
Dmitry Sikorsky
4/30/2011 1:05 AM
That's exactly what I was looking for!
Thank you!
Gravatar
# re: ASP.NET MVC View Model Patterns
Jesse
5/7/2011 8:22 PM
What about the service layer? I see your accessing the repository directly from your view model builder. Typically I like to go through my service layer to get to my data layer.
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
5/10/2011 8:52 PM
@Jesee - Both a repository and service layer can be appropriate given the context of your application.
Gravatar
# re: ASP.NET MVC View Model Patterns
P Desai
8/17/2011 10:47 AM
Nice post. I am looking for some suggestion all over the internet but very few post address this topic.
I have following arch.

DataModel <--> Business & Repos <--> DomainModel <--> Web (and Business)

I am thinking of creating view model in my Web for all my views the problem then becomes yet another conversion from Domain Model to ViewModel and vice a versa. Do you know if its a good idea to convert my domain model into view model?

Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
8/20/2011 11:58 AM
@Desai - that pattern is fine - it's most like #3.
Gravatar
# re: ASP.NET MVC View Model Patterns
Zane
8/25/2011 2:48 AM
Great post. This is the first discussion I've found about how to structure more complex applications.
Gravatar
# In pattern 3, where is MototcycleData in your MotorcycleViewModel class created by MotorcycleViewModelBuilder?
simon
11/11/2011 2:51 PM
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: }

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: }
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve
11/11/2011 7:15 PM
@simon - MotorcycleData is a property of the MotorcycleViewModel.
Gravatar
# re: ASP.NET MVC View Model Patterns
Vishnu
2/6/2012 3:59 AM
Really nice article. Very well explained in simple language.

Do you have a post or article on how injection is handled here for the business or DB services.
Gravatar
# re: ASP.NET MVC View Model Patterns
Alan Fisher
6/5/2012 3:44 PM
Excellent article, I would like to see a functional example project that follows pattern # 3 from beginning to end. Do you know of any on the web that closely follows it using real world example?
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve Michelotti
6/8/2012 5:36 PM
@Alan - There are numerous examples you should be able to fine. Here's one from a presentation a did a while back: http://archive.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=michelotti&ReleaseId=3288
Gravatar
# re: ASP.NET MVC View Model Patterns
Alexander
8/29/2012 4:47 PM
Hi, great post.
I have a question according to ...DataModel classes. In our project our view models (MyViewModel) contain properties of ..DataModel (MyDataModel) classes. Service layer works with DataModels and maps them into data access objects (for example Entity Framework). So, the main idea of the data model classes in this context is to transfer data to service layer. So, point on that, can I rename MyDataModel class into MyDataDTO?

Thank you.
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve Michelotti
8/29/2012 4:49 PM
Sure, you can rename without problem. It does, however, seem a little odd that the data model classes hang off your view model classes in a property.
Gravatar
# re: ASP.NET MVC View Model Patterns
Chris Nevill
8/31/2012 7:09 AM
Presumably MotorcycleData could inherit from Motorcycle instead of redefining it's attributes?
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve Michelotti
9/9/2012 2:12 PM
@Chris - One of the advantages to option #3, is you get the ability to change the shape *if necessary*. You also have the ability to put view model validation on it. Inheritance doesn't give you any of these advantages.
Gravatar
# re: ASP.NET MVC View Model Patterns
NETDevNewbie
1/9/2013 3:24 PM
I was searching for solution to my problem in my app and that is to display the details data of a specific client. I need to merge data from multiple models and return it as a single model to the view. I found a solution online and I want to know if the code is efficient and correct based on your explanation (btw, the code is working but I want to know if the solution is the right one).

In my ViewModel, here's the code:

public class MyDetailsViewModel
{

public tblMaster Master { get; set; }
public tblDetails Details { get; set; }
public tblClients Client { get; set; }
public tblInsurance Insurance { get; set; }
public tbladdress Address { get; set; }
public tblstate States { get; set; }
}


In my controller:
public ActionResult Details(int id = 0)
{

MyDetailsViewModel lopDetails = new MyDetailsViewModel();

var detailsData =
from lc in db.ltblDetails
join m in db.tblMaster on lc.master_id equals m.master_id
join cl in db.tblclients on m.master_id equals cl.master_id
join i in db.tblinsurances on lc.insurance_id equals i.insurance_id
join a in db.tbladdresses on i.address_id equals a.address_id
where lc.details_id == id
select new MyDetailsViewModel{ Master = m, Details = lc, Client = cl, Insurance = i, Address = a };

if (detailsData == null)
{
return HttpNotFound();
}

return View(detailsData );

}

In my View:
I reference it this way:
<% foreach (var item in Model)
{ %>
<%= Html.TextBox("txtId", item.Master.caseNum)%>
<%= Html.TextBox("txtId1", item.Client.clientname)%>
}%>
Gravatar
# re: ASP.NET MVC View Model Patterns
NETDevNewbie
1/9/2013 3:28 PM
CORRECTION on my previous post:

This line of code --
MyDetailsViewModel lopDetails = new MyDetailsViewModel();


-- is this (typo error)
MyDetailsViewModel detailsData = new MyDetailsViewModel();
Gravatar
# re: ASP.NET MVC View Model Patterns
Steve Michelotti
1/10/2013 9:09 AM
@NETDevNewbie - That looks fine to me.
Gravatar
# re: ASP.NET MVC View Model Patterns
Laptops
5/29/2013 2:59 PM
Figuring out the MVC is going to take me a little longer than I hoped, but good tut on constructing view models.
Gravatar
# re: ASP.NET MVC View Model Patterns
Larry
4/9/2014 12:40 PM
So 5 years after your post I can't tell you how happy I am to have found it. If finally and clearly sets the pattern - or way to approach the pattern - in my mind. Thanks!

Post Comment

Title *
Name *
Email
Comment *  
 

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud