I'm trying to find out what the issues are on each side of either composing a DTO that has the model+drop down lists,etc... vs passing those extra objects/lists in 开发者_C百科the ViewData. I haven't come up with an argument against using ViewData besides the strongly typed purist in me.
I thought I would ask what else I might need to consider?
It's a matter of encapsulation. I put everything I need to render the view (including dropdown list data and server-side validation) into the ViewModel object. That way I don't have stuff scattered to the high winds.
I'm not a purist, but the idea of pushing untyped information into the ViewData, and casting it to the correct type in the view, just feels uncomfortable to me. I have yet to find a situation where this makes sense, unless I am passing small bits of information to the view that have nothing to do with the ViewModel or the underlying database model.
Small bits of information that I would put in the ViewData might include things like paging links, or perhaps ReturnUrl references that I don't want to put in the Url as a parameter, nor do I want them polluting my ViewData object.
For testing purposes, it's better to keep most things in a custom ViewModel. You can more easily run proper tests on the data, - even without firing up the web server, so you win on performance as well.
Terje's point about testability is important. Also the performance point is obvious (no dictionary lookup or casting).
On the other hand, a weekly-typed ViewData mimics the Rails world. In the rare case where you have to translate a project from Rails to ASP.NET MVC in a very limited amount of time (which I actually had) this makes the process more direct. Which really cuts to the core of the one Pro for weakly-typed ViewData: rapid app dev.
Before I'm beat into oblivion with downvotes, I'm not advocating it as correct or proper. It's simply undeniable that using explicit ViewModels requires more dev resources to develop. What's saved in dev resources, is lost in performance, testability, and long-term maintainability.
精彩评论