开发者

ASP.NET MVC2: How to render a view if has multiple different models

I know that view model can be used for rendering a view, but if a page needs different mod开发者_StackOverflow中文版els, how can I pass them to the view? And how do I use them?


If you need to pass multiple models then create an all-encompassing model that has the smaller models hanging off as properties.

For instance, let's say you are going to display a page for managing groups of users for your app. You would probably need to pass an IEnumerable<UserDisplayModel> and also an IEnumerable<GroupDisplayModel> to the view. Create a new display model like this:

class GroupManagementDisplayModel
{
    public IEnumerable<UserDisplayModel> Users { get; set; }
    public IEnumerable<GroupDisplayModel> Groups { get; set; }
}

Pass instances of this model to your view instead.


If you find that you want to do this a lot and that you don't much care for creating lots of small types, then you can use .NET 4's dynamic type:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

In your action, pass an anonymous type to your view:

return View(new { Users, Groups });

The reference them in your view as you would otherwise.

You lose intellisense and strong typing this way, but unless you're compiling your views (which requires manually editing your .csproj file and makes the build much slower) then you don't have compile time checking on your views anyway.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜