Click here to Skip to main content
14,691,021 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I was debating with my co-worker on this issue. Is it absolutely necessary to create view models of models even if working with the model directly works just fine since you don't need data from other models in the view?

What I have tried:

The models, in this case, don't have any logic in them, they're pocos. Logic comes from the respective repository.
Posted
Updated 1-Oct-20 2:45am
Comments
Sandeep Mewara 1-Oct-20 5:55am
   
MVC follows Model-View-Controller.

ViewModel comes in MVVM.

You have tagged MVC, how is Viewmodel in picture here?
Member 13029506 1-Oct-20 6:07am
   
The thing is, that my co-worker and I are working with MVC but he is insisting on working with view models in MVC as well

You don't have to use them, but they can make life simpler.

For example, image you want a view to edit an entity. That entity includes relationships to other entities, which you want to display as drop-down lists. You don't want to add the list of options to the entity class, so you have two options:
  • Store the option lists in the ViewBag. You will get no compile-time validation that the keys you use in the controller match the keys you use in the view. And you will probably need to insert a cast in the view, since the ViewBag properties return dynamic, and the HTML helper methods can't be used with dynamic values.
     
  • Use a view-model, and store the list in that. No need for ugly casts in the view, and the compiler will check that the property you use in the view matches a property on the view-model. (Although it won't guarantee that you've used the correct property!)

@Html.DropDownListFor(m => m.SomeProperty, (IEnumerable<SelectListItem>)ViewBag.SomePropertyOptions, "(None)")
vs:
@Html.DropDownListFor(m => m.SomeProperty, Model.SomePropertyOptions, "(None)")
   
You don't have to, be pragmatic.
If data in your model is 1:1 with data you want to display on view, using model is just fine.
On other hand if you want to display only portion of data or some customization of it view model is IMO better approach.
Same goes if you want to add some extra functionalities which are not (or should not be) part of an model.

Lines are often blurred, use whatever fits your needs, but be consistent in your approach.

Those are my 5 cents.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900