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

送分小仙女□ 提交于 2019-12-05 17:27:30

An alternative to tvanfosson's solution is to create a strongly-typed view so that you get cvompile-time checking and less "magic strings."

Example...

Assume you have the 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 view. This will allow you to access the passed in view data with intellisense if you setup the view registration line up to use it (notice the part. This means the Model property will be an instance of the passed in viewdata argument into 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 wouldn't use this code verbatim.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!