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?
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.
The ViewModel is essential when you want a separation of concerns between your DomainModel (DataModel) and the rest of your code.
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.
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.
No, it's not bad at all. It's perfectly fine code. It allows you to reuse portions of view models between different views.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With