Reputation: 143
Been working on a pet project on the side to learn asp.net mvc better. My question is about viewmodels in mvc. I understand the controller is supposed to handle the interaction between the view and the model. I feel like I keep having to create viewmodel classes to combine information from the models to pass to the view.
Is this bad practice? Should I be doing more of the logic elsewhere and cut down on the viewmodels?
At the moment I've almost got a viewmodel for just about every one of my main views. But I definitely don't want the view to access the model directly.
Upvotes: 8
Views: 894
Reputation: 18068
Using lot of viewmodels creates mess in your project. It is much better to just create a Tuple
in the controller then pass it.
Upvotes: -3
Reputation: 4886
Great answers here, and here is my view on why a lot of view models are not an issue. Your ViewModels are a nice way of separating your pure Data Access Objects or even your Domain Objects from your presentation layer and provide a dumbed down version of those objects for your views to consume.
Your views are supposed to be dumb and for me personally, what I try to achieve is to massage my domain model into a ViewModel for my view to consume.
Upvotes: 0
Reputation: 156
No, all your views should be strongly typed, so using for each view one viewmodel is best practice. Here is very nice article about viewmodels.
Upvotes: 8
Reputation: 19821
Nothing bad in this. As much your viewmodel closer to view as better.
Model could not particullary match View, so you use ViewModel class for that.
Upvotes: 0
Reputation: 123
The more viewmodels you use the better. The viewmodels allow you to create a single object that can contain different types of data from your models. These are very useful when creating templates. Also, this is very useful when using JQuery and Ajax since its a nice way to pass data into your controller and then directly to the DOM. In my opinion, use as many viewmodel as you desire.
Another thing that you might consider is to try to have better design of your model. I personally try to build my model just like a sql database and follow the normalization forms. You should not have to create a new viewmodel for each view in addition to the models you already have. If you need to pass information to the view that is not part of the model you are using, use ViewData or ViewBag. These are passed as an object so you will have to cast them to the appropriate class.
Upvotes: 2