是否有可能发送多个模型对象的ASP.NET MVC视图? [英] Is it possible to send more than one model object to an ASP.NET MVC View?

查看:106
本文介绍了是否有可能发送多个模型对象的ASP.NET MVC视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的开始页面,我想显示几个,我对其他的页面不同的列表中的第一个项目 - 在这里有点像近期页面上,会显示这两个最新文章和最近的评论。在我来说,我想列出在留言簿上最近的两个职位,而接下来即将发生的事件。

On my start page, I'd like to display the first items from several different lists that I have on other pages - somewhat like the "recent" page here on SO displays both recent posts and recent comments. In my case I want to list the two most recent posts in a guest book, and the next upcoming event.

为了做到这一点,我怎么能传递一些模型对象,以我的看法?它甚至有可能?如果不是,那应该怎么办呢?

In order to do this, how can I pass several Model objects to my View? Is it even possible? If not, how should it be done?

推荐答案

这是替代tvanfosson的解决方案是创建一个强类型的视图,让你得到cvompile时检查,少魔弦。

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

示例...

假设你有类:

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);
}

和,最后...在你看来。这将允许您访问传入的视图数据与智能感知,如果你设置视图登记排队使用它(注意的部分。这意味着Model属性将成为一个实例传入的可视数据参数到视图的方法你控制器。

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>

当然,这只是一个演示,我不会用这个code一字不差。

Of course this is just a demo and I wouldn't use this code verbatim.

这篇关于是否有可能发送多个模型对象的ASP.NET MVC视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆