Reputation: 11143
Should i consider ASP.NET MVC ViewModels only containing flat and primitypes types or it should contains complex Core/Domain model types ?
I'm looking for best practices.
Thanks.
Upvotes: 4
Views: 376
Reputation: 180898
Do what makes sense.
There are no authoritative sources that will tell you that using ViewModel with primitive types is going to kill kittens, because they would be wrong. And for every expert out there who tells you that using ViewData with magic strings is perfectly OK, there will be purists out there who will tell you that strongly-typed objects are the only way to go.
I write applications that read from a database and display data in a web page. I have tried it both ways (using ViewData and using a ViewModel object), and I am happiest when I have a ViewModel object to project into the web page. The ViewModel class is a place to encapsulate things like validation and view logic, if I need them, and it provides the data structure and strong typing that I like.
If I just want to display a record from one of my Linq to SQL classes, and I don't need extras such as dropdown data lists, I might use the Linq to SQL object directly. But if I do have extras, I put everything into a ViewModel class, and project that ViewModel instance (or an IEnumerable or IQueryable of them) into the view.
So I seldom use ViewData, but that's just my style. It's nice to know that it's still there if I need it.
Upvotes: 6