开发者

Pattern of sending multiple objects to the View in ASP.NET MVC

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 obje开发者_如何学编程ct 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?


You may define your strongly typed View with Data Transfer Object.

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

public class FrontPageDTO
{
    public List<Student> StudentList { get; set; }
    public List<Teacher> TeacherList { get; set; }
}

Then pass an instance of this DTO to your View.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜