I have a question about asp.net mvc-2 strongly typed partial views, and view models.
I was just wondering if I can (or should) have two strongly t开发者_运维技巧yped partial views on one page, without implementing a whole new view model for that page.
For example, I have a page that displays profiles, but also has an inline form to add a quick contact. Each of these entities already has it's own view model, i.e I have a ProfileViewModel and a ContactViewModel.
So my view needs two strongly typed partial views, one using an IEnumerable List of ProfileViewModels, and one using a ContactViewModel. Is it possible or desirable to avoid making a third view model, an 'IndexViewModel' for this page, which holds a list of ProfileViewModels and a ContactViewModel? Is not implementing this view model bad practice, or tidier as it results in less view models?
Thanks!
If both partial views require view models that are already defined, then the page that hosts those partials needs to supply the view models somehow. It is easy to imagine how an IEnumerable<ProfileViewModel>
must be supplied to the containing page, as the contact information likely arrives from the back end. Does the ContactViewModel
actually hold any data? If not, you might be able to create it on the spot in the containing page's view, and get away with passing only a IEnumerable<ProfileViewModel>
to it.
Otherwise, the containing view needs to receive both a IEnumerable<ProfileViewModel>
and a ContactViewModel
. The option I would lean towards is indeed defining a new view-model that has data members for those two values. It's somewhat better documented and allows for some better compiler type checking than the alternative of passing those values via ViewData[]
.
Somewhat implied in your question is the notion that creating a view model is a chore. That may well indeed be the case for the partial views, if the view model's definition merely mirrors that of some back end entity. If that is the case, you might want to consider passing the back end entity directly instead of duplicating its definition and content in a view model.
Finally, view-models are just a tool. Use them if they add value. Some application gain clarity, documentation and loose-coupling advantages from using distinct view-model classes. Others, often smaller apps, don't gain enough to merit the overhead. There's nothing inherently 'bad practice' about not implementing view models (or any other design pattern, for that matter.) It's a design choice you can feel comfortable about if you have a reasonable argument in its favor.
精彩评论