Pankaj Upadhyay
Pankaj Upadhyay

Reputation: 13584

When to use ViewModel and when not in Asp.net MVC

AFAIK, there are two ways of passing data to the view from controller : one being loosely typed(using ViewBag or ViewData), other being strongly-typed. Most recommend the latter because of strong compile-time checking.

In a dynamic web application, we come across scenarios when there is a requirement to pass multiple entities from the controller to the view. In that case, one can either pass a single entity as a model and rest in ViewBag dictionary. Or One can make an entirely new ViewModel class merging the various entities and then passing it to the view.

Recently, I encountered such an issue; I needed to pass a category model which had list of subcategories and products registered with it as properties. And then in the view, I needed to diplay the subcategories along with making sure that pagination occurs on products collection if they are more than 10. Therefore i couldn't use a strongly typed view for either Category Model or Product Model.

The Solution was presented by follow peers, tvanfosson and Ufuk Hacıoğulları(Many thanks to both) in this Post. And that is to use a ViewModel. I am still trying to understand and work on it and it seems to be the proper solution.

Question : Is this a better way to handle such situations ? Also, when is it recommended to use ViewModel and when to bypass it in favour ViewBag & a Model.

Upvotes: 2

Views: 248

Answers (1)

Jan
Jan

Reputation: 16042

The one and only purpose of a Viewmodel class is to contain (strongly typed) data to be sent to a view by an action method.

So as the answers in your referred question suggest create a Viewmodel class which contains properties for all the data you need in your view.

The advantage of Viewbag usage is that you don't have the overhead to create a separate class. The disadvantage is that you don't have compile time type checking and intellisense available.

Upvotes: 6

Related Questions