tags:

views:

569

answers:

3

im not sure if there is a difference in these two methods. If so, which would be considered the better practice when submitting more than one object to the View.

1- Having the controller make separate calls to the datalayer for each object model and then wrapping the objects in a model to send to view.

2- Defining a "presentation" model and having the controller call that single model to send to the view.

3- other...?

+3  A: 

You should send to the View a single object, sometimes termed a ViewModel object, containing all the data (including domain model objects) that the view will need.

Justice
+3  A: 

I'm assuming here that you have a view that presents some information from more than one model, perhaps in a list format. For example, you may have a model of a customer which has a set of contacts, but in your list you want to choose to show some of the customer details along with the name and phone number of the primary contact. What I would typically do in a situation like this is define a specific "presentation" model that consists of just those details that I may want to show in this combined view. It would typically be a read-only model. Using LINQ to SQL I might even define this as a table-valued function (to support search) and associate it with a view that encapsulates the join of the various tables. With both you can add the view-based "presentation" model to your DBML and associate the table-valued function with it as a method on the data context.

I prefer doing this because I believe that it is more efficient in terms of queries to construct the query on the server and simply use it from the code. If you weren't using the table-valued function for searching, you might be able to construct the query in code and select into a "presentation" class. I would favor an actual class over an anonymous type for ease of use in the view. Getting the properties from an anonymous type in the view would be difficult.

tvanfosson
A: 

The scenario is a prime example of the usage of ViewModel pattern. As a less recommended alternative you can use ViewData. But using ViewData you loose the type-safety, compile checking and intellisense.

Here's an article that goes into comprehensive length on how to use ViewModel pattern in ASP.NET MVC.

http://theminimalistdeveloper.com/2010/08/21/why-when-and-how-to-use-typed-views-and-viewmodel-pattern-in-asp-net-mvc/

Specifically it discusses what it is, how it came about and when best to use it and how it can be implemented in ASP.NET MVC.

Enjoy !

Bikal Gurung