2

I know that view model can be used for rendering a view, but if a page needs different models, how can I pass them to the view? And how do I use them?

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, this is what you're going to want to do. Then you'll have access to intellisense to help you select what attributes you want to use.
1

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.

1 Comment

No problem. Personally I don't use this approach as I like intellisense, and Resharper makes generating small types quick and easy, but I included this answer here for completeness.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.