Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use a lot of viewmodels in asp.net mvc

Tags:

asp.net-mvc

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.

like image 455
Deekane Avatar asked Aug 25 '11 04:08

Deekane


People also ask

Should you use ViewModels?

The ViewModel is essential when you want a separation of concerns between your DomainModel (DataModel) and the rest of your code.

Can a view have multiple models?

Yes, you can use Tuple (brings magic in view having multiple model).

How many views does the model can have in MVC?

ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible.

Can one action have multiple views?

No you cant have multiple views returned from single action. In case you want in that way then, you can do it like this, Parent View Partial View inside Parent View.


1 Answers

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.

like image 77
Petr Klíma Avatar answered Sep 27 '22 23:09

Petr Klíma