Is it possible to send more than one model object to ASP.NET MVC View?

On my start page, I would like to display the first elements from several different lists that I have on other pages - something like the β€œlast” page here, on SO displays both recent posts and recent comments. In my case, I want to list the last two entries in the guestbook and the next upcoming event.

To do this, how can I pass multiple model objects into my view? Is it possible? If not, how to do it?

+4
source share
1 answer

An alternative to tvanfosson's solution is to create a strongly typed view so that you can check the cvompile runtime and fewer "magic lines".

Example...

Suppose you have a class:

public class FrontPageViewData { public List<Post> Posts { get; set; } public List<Comment> Comments { get; set; } } 

Then in your controller ...

 public ActionResult Index() { FrontPageViewData viewData = new FrontPageViewData(); viewData.Posts = DB.Posts.ToList(); viewData.Comments = DB.Comments.ToList(); return View(viewData); } 

And finally ... in your opinion. This will allow you to access the data passed to the view using intellisense if you configure the view registration line before using it (note the part. This means that the Model property will be an instance of the passed viewdata argument to the VIew method in your controller.

 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<FrontPageViewData>" %> <asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server"> <%= Model.Posts.Count().ToString(); %> <%= Model.Comments.Count().ToString(); %> </asp:Content> 

Of course, this is just a demo, and I would not use this code verbatim.

+11
source

All Articles