Tuesday, October 27, 2009

ASP.NET MVC Translated for the Web Forms Programmer (5 in a series) - What the Frig is a View Model?


I wanted to expound on something very important that I kind of glazed over in the last post, View Models. View Models are something that is very pivotal to MVC and were one of the hardest things for me to understand. I feel like it's important to go over them in depth so you can understand them as well. 

 

I actually don't love the concept of a View Model, it's a little muddy for me. I understand that it is important because it allows the View to do what it was made for: rendering and displaying elements. However, like any other programmer I like things clean and easily defineable. I like concrete answers, and non-redundant interfaces. A View Model is none of these things. It is an arbitrary collection of data gathered for the express purpose of conveiniently grouping your views. 

 

Before I completely talk you out of them I must clarify that I love using them in my MVC applications because it alows me to seperate my OO archtecture from my Views. You know, seperation of concerns and all that. 

 

So how do I get started?  A View Model is simply a class that you build to aggregate the data you want to display in your view. 

 

Let's say I have a class Car and a class Train. I want a view to display all the ways I can get from New Jersey to New York. I have a train schedule and a list of rental cars. The classes Train and Car are not associated to each other in my data model. So, what to do? That is where our View Model comes in. They are pretty easy to create, my Car/Train view Model is called TransportationViewModel and it looks like this:

 


To populate my View in my Controller I create an action and when I return my View I pass in an instance of my TransportationViewModel. Like this:

 


As you can see this is just a simple class that contains both a list of Cars and a Train. My view will be strongly typed and inherit from this View Model. This is how it will look:

 


As you can see, my View Model allows me to pass my Data to my view and I don't have to muss with my objects or my model. 

 

 When it comes to data manipulation you want to keep that in the Model, not do it in your View Model. Unless what you are messing with is specifically for that particular view. 

 

Now, the question of the year is: "Do I need a new View Model for each View?" The answer is: it's up to you. If you only need one class in your particular view than you don't need one. However, I find that to be very rare. 


51 comments:

  1. Hi Sara,
    Great write up! I like the humor you injected through out, made it a fun read! :)
    I wanted to comment on this piece,
    It is an arbitrary collection of data gathered for the express purpose of conveiniently grouping your views.
    This is partially true; At times, more often than not, you don't need all the data from your model within your view. A ViewModel is nothing more than a subset snapshot of your data that doesn't have all the extra pieces from your domain model.
    For example, in your sample you use the Car/Train models within your view. Say that you're using the ActiveRecord pattern for persisnce and that your objects have the .Delete() method on them. Since these are available in the view, nothign stops a developer from calling them. So now you've exposed functionality into a different concern of your application and set yourself up for possible side effects.

    ReplyDelete
  2. Nice post. The spark equivalent of that template look something like:
    viewdata mode=Transportation.ViewModels.TransportationViewModel /
    set title=List Vehicles /
    h2List Vehicles/h2
    h4Cars:/h4
    for each=var c in Model.Cars
    Make: b${c.Make}/b
    Model: b${c.Model}/b
    /for
    h4Train:/h4
    b${Model.Train.Line}/b
    b${Model.Train.Schedule}/b
    Even for a simple example, there's less noise, and I've
    added html encoding to prevent possible injection attacks.

    ReplyDelete
  3. I think that yet another way to think about the view model is you literally say the phrase 'presentation model'. Such that if you have a complicated domain model that has a deep object graph you will see very quickly how cumbersome that can be to work with in your views. Having a view model which flattens that domain model will make that easier to work with. You are modeling for your presentation layer.
    Just my two cents...

    ReplyDelete
  4. car parts ware houseJune 30, 2010 at 6:27 AM

    Thanks for great tutorial :)

    ReplyDelete
  5. Peluang Usaha Ahasu GnaulepJune 30, 2010 at 6:27 AM

    I was looking the some useful information that was referred to in the above article in other websites, but this article was the most helpful so far. Thank you.

    ReplyDelete
  6. nowGoogle.com Adalah Multiple Search Engine PopularJune 30, 2010 at 6:27 AM

    I don�t know If I said it already but this so good stuff keep up the good work. I read a lot of blogs on a daily basis and for the most part just wanted to make a quick comment to say I�m glad I found your blog. Thanks.

    ReplyDelete
  7. Kompetisi Website Kompas MuDA - KFCJune 30, 2010 at 6:27 AM

    I�ve really enjoyed reading your articles. You obviously know what you are talking about! Your site is so easy to navigate too, I�ve bookmarked it in my favourites.

    ReplyDelete
  8. nowGoogle.com adalah multiple search engine popularJune 30, 2010 at 6:27 AM

    the truth is your post give me news inspiration

    ReplyDelete
  9. nowGoogle.com adalah multiple search engine popularJune 30, 2010 at 6:27 AM

    lead from search engine i got something after read your post

    ReplyDelete
  10. Nowgoogle.com Adalah Multiple Search Engine PopularJune 30, 2010 at 6:27 AM

    Very outstanding web. The content here is truly important. I will share it with my friends.

    ReplyDelete
  11. festival museum NusantaraJune 30, 2010 at 6:27 AM

    but this article was the most helpful so far. Thank you

    ReplyDelete
  12. Nowgoogle.com Adalah Multiple Search Engine PopularJune 30, 2010 at 6:27 AM

    great blog very usefull thank

    ReplyDelete
  13. webthesurfi rugs webdesignJune 30, 2010 at 6:27 AM

    This so good stuff keep up the good work. I read a lot of blogs on a daily basis and for the most part just wanted to make a quick comment to say I�m glad I found your blog.

    ReplyDelete
  14. Hi thanks for your nice article

    ReplyDelete
  15. Really nice post there..

    ReplyDelete
  16. Anti Wrinkle CreamJune 30, 2010 at 6:27 AM

    I love your post much,,,

    ReplyDelete
  17. i love your writing style...

    ReplyDelete
  18. nowGoogle.com Adalah Multiple Search Engine PopularJune 30, 2010 at 6:27 AM

    nice post, I have project about multiple search engine

    ReplyDelete
  19. I'm still confuse with the script above

    ReplyDelete
  20. Thanks for sharing

    ReplyDelete
  21. Wait for the next tutorial...

    ReplyDelete
  22. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon.

    ReplyDelete
  23. Hey, I love your blogs layout and style of your articles. I will subscribe for your feed please keep posting! Big thanks for the useful info I found here

    ReplyDelete
  24. Thanks for sharing! very good post.

    ReplyDelete
  25. thanks for great share

    ReplyDelete
  26. I know it is hard to study View Models as me too.

    ReplyDelete
  27. i dont like the concepts for view models too.. nice share thanks..

    ReplyDelete
  28. This is my first time I visit here. I found many interesting things in your blog, especially the discussion. Of the tons of comments on your articles, I'm not the only one with all the enjoyment here! Keep up the excellent work.

    ReplyDelete
  29. Thank you for the tips. great post.

    ReplyDelete
  30. Kerajinan KuninganJune 30, 2010 at 6:27 AM

    I read blogs on a similar topic, but i never visited your blog. I added it to favorites and i'll be your constant reader.

    ReplyDelete
  31. Interesting post... Thank you for information shared!

    ReplyDelete
  32. Lowongan Kerja terkiniJune 30, 2010 at 6:27 AM

    i found your article through search engine. thanks for the share. maybe i'll back later.

    ReplyDelete
  33. Wholesale Brand Name ClothingJune 30, 2010 at 6:27 AM

    My friend genuinely enjoyed your article. It seems like you have placed a lot of effort into your post and this world need a lot more of these on the web these days. I do not have a bunch to to say in reply, I only this minute wanted to comment to reply well done.

    ReplyDelete
  34. It was a pleasure to read your articles. I got lots of useful stuff from your site. I was totally unfamiliar with many of subjects, but now I feel pretty confident in it! Thanks

    ReplyDelete
  35. I admire time and effort involved in your high quality and informative articles. But at the same time they are simple to understand and helpful. I am looking forward to seeing your future updates.

    ReplyDelete
  36. Easy Ways To Make MoneyJune 30, 2010 at 6:27 AM

    Hello webmaster I like your post. I found your site on del.icio.us today and really liked it. I bookmarked it and will be back to check it out some more later.

    ReplyDelete
  37. Buy Sell Products ServicesJune 30, 2010 at 6:27 AM

    I don�t know If I said it already but this so good stuff keep up the good work. I read a lot of blogs on a daily basis and for the most part just wanted to make a quick comment to say I�m glad I found your blog. Thanks.

    ReplyDelete
  38. Its A Cool Post dear...
    simply informative...
    www.wholesaleclothingworld.com
    Wholesale Brand Name Clothing
    Must Look...

    ReplyDelete
  39. Its an amazing post...
    May b helpful 4 us too�
    Hope u will provide us more info. On that ....
    www.icater.ca
    Toronto Catering
    Must Look...

    ReplyDelete
  40. This post shows the information which is close to standard.
    Hope next You will again post a nice Artical/Information.
    Visit us:
    Mathew Day:
    www.mathewday.com

    ReplyDelete
  41. SEO friendly blogger templateJune 30, 2010 at 6:27 AM

    I do not have a bunch to to say in reply, I only this minute wanted to comment to reply well done. Thanks.

    ReplyDelete
  42. That is a truly fantastic piece of work.

    ReplyDelete
  43. just wanted to let you know I enjoy reading your blog and hope you will continue writing them for a long time to come.

    ReplyDelete
  44. Studies this matter, lacks the time, but is lacks diligently#.

    ReplyDelete
  45. I often dream of that clueless closet app as well. (My first Java applet was a dress-up game.) I think it'd make a good mobile app - take pics of your clothes or draw them, catalog them, remember your favorite outfits. Bonus if it super-imposes them on you and tweets them out for ratings.

    ReplyDelete
  46. I often dream of that clueless closet app as well. (My first Java applet was a dress-up game.) I think it'd make a good mobile app - take pics of your clothes or draw them, catalog them, remember your favorite outfits. Bonus if it super-imposes them on you and tweets them out for ratings.

    ReplyDelete
  47. As you can see, my View Model allows me to pass my Data to my view and I don't have to muss with my objects or my model.
    http://www.mbtusasale.com

    ReplyDelete
  48. I wanted to expound on something very important that I kind of glazed over in the last post, View Models. View Models are something that is very pivotal to MVC and were one of the hardest things for me to understand. I feel like it's important to go over them in depth so you can understand them as well. http://www.uggsaleaustralia.com

    ReplyDelete