Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to have a ViewModel with a property typed as another ViewModel in ASP.NET MVC

Would it be considered bad practice to have a viewmodel that has a property of another view model?...as in:

public class PersonViewModel
{
     public PersonJobViewModel Peron { get; set;}
     //other properties here...
}

EDIT

A little more about my particular situation:

I have a view model that currently contains 2 domain classes. I pass this viewmodel to a view that loads 2 partials views(one for each domain class in the viewmodel)

So with this I end up passing pure domain models directly into the partial views.

My thinking is that I can make a view model for each domain model that go to the partials...and then wrap those 2 in another viewmodel that gets passed to my parent...

or is there a better way to accomplish this?

like image 823
stephen776 Avatar asked Apr 15 '11 13:04

stephen776


People also ask

Can a ViewModel have multiple models?

ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method. In the above example, we have the required View model with two properties.

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 I use ViewModel in MVC?

In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

What is the difference between ViewModel and model in MVC?

A model is usually more closely related to how your data is stored (database, services, etc.) and the model will closely resemble those. The ViewModel on the other hand is closely related to how your data is presented to the user. It is usually a flatten version of your model, denormalized, etc.


2 Answers

No, it's not bad at all. It's perfectly fine code. It allows you to reuse portions of view models between different views.

like image 151
Darin Dimitrov Avatar answered Oct 16 '22 12:10

Darin Dimitrov


I don't believe that I would consider it bad practice to aggregate one ViewModel within another. I can see an advantage, like being able to render a partial view or use an EditorFor of the aggregated view model.

like image 34
CAbbott Avatar answered Oct 16 '22 14:10

CAbbott