1

I have doubts whether every view should have its own ViewModel or should I pass the plain model where there is no need for ViewModel? (What concerns me is that if I start to mix these two concepts, then I will end up with jungle later on)

I tried to google it but no one talks about that, every post I run into just explains the purpose of ViewModel and I know that the main purpose of ViewModel is so you can pass multiple models to view.

keipala
  • 768
  • 2
  • 7
  • 19
Genato
  • 520
  • 8
  • 20
  • 2
    there is best explanation on this topic check out:-https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc – Mr. Roshan Jun 02 '18 at 12:02
  • _that main purpose of ViewModel is so you can pass multiple models to view_ No! A view model represents what you want to display/edit in the view –  Jun 02 '18 at 22:53

2 Answers2

1

It depends.

In many use cases the main purpose is not to expose fields to being bound on form submission that the user shouldn't be able to update. I wouldn't slavishly create them when not needed but it depends on the developers and their level of understanding on when and why you use viewmodels vs domain/ef models. Also application code base size makes a difference.

Maybe you need select lists, maybe you want to convert some properties to different types. Lots of reasons to use them. However it is more code and mapping code even if you use a tool like AutoMapper. So they cost time to implement but maybe they fix problems and save other time? Maybe they fix a security problem? Maybe doing them all the as view models helps juniors understand? Maybe you would rather do the setup of a viewmodel at start than convert code later when it is really needed?

Consistency can help but doing a bunch of extra work may not be worthwhile. Best practice for me isn't best practice for you.

Consider the costs and benefits for your project and team . E.g. maybe your project is internal and no one is going to try to hack via adding data to submission

GraemeMiller
  • 11,973
  • 8
  • 57
  • 111
1

There are couple of reason to choose ViewModel over DomainModel.

1) First thing first is the security. Imagin you have a view for changing the password. If you pass the domain model to the view. probably you are exposing a lot of properties which is not necessary and it may cause a security problem. There is no reason to expose properties like LastLoginDate, IsActive, IsEnabled, NumberOfFailedLogin and so on for just changing the password.

2) The second reason is reducing logic from the view. If you pass a Domain class to the view, Possibly you need to add some extra logic for hiding extra properties or shape it as you like or adding logic based on the route and etc.

3) Because of the architecture. Exposing domain model to the view cause tightly coupling between your presentation layer and domain model which is not good at all.

Mostafa
  • 3,002
  • 10
  • 52
  • 79