views:

63

answers:

4

I am doing my first project in ASP.NET MVC and using the NerdDinner sample project in ScottGu's book as a guide. In his project, all his strongly typed views neatly correspond to the objects he defined (e.g. Dinner). That is not really reality of a business application.

For instance, in my app, a page (e.g. View) gets most of its information from the primary object that the strongly typed View was created from. But it also has to display information from a dozen other objects.

So, what is the preferred pattern of passing all this information into the View?

  • Do I pass the primary object via the Model and the rest of the info via ViewData?
  • Do I create a master object for each View that encompasses all the data I might need for that page?
  • Is there a better approach?
+2  A: 

You may define your strongly typed View with Data Transfer Object (http://martinfowler.com/eaaCatalog/dataTransferObject.html).

Ex: Your View need Student list and Teacher List, then you may define a data transfer object (wrapper).

public class FrontPageDTO
{
public List StudentList {get; set;}
public List TeacherList{get; set;}
}

Then pass instance of DTO to your view

Anton Setiawan
+4  A: 

The "master object for each view" is called a View Model. That is my preferred solution.

Aaronaught
+1  A: 

In addition to View Models you can use Action Filters to pass "reference data" from controllers to views. See article about it.

kilonet
+1  A: 

Try implementing ViewModels for your application. Here is an example of creating a simple ViewModel.

http://highoncoding.com/Articles/659_Implementing_ViewModel_in_ASP_NET_MVC_Application.aspx

azamsharp