发送到单个视图实例多个模型 [英] Multiple models sent to a single view instance

查看:83
本文介绍了发送到单个视图实例多个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的术语可能的方式在这里下车,但基本上我想多个数据模型传递给视图。为了帮助在提供有关的问题,借这个例子:

My terminology is probably way off here but basically I'm trying to pass multiple data models to a view. To help put the question in context, take this example:

说我是做一个博客。当我登录我想在主屏幕上显示的所有新的未经批准的评论列表,以及最近注册用户的列表,以及最近提交的博客文章列表。

Say I was making a blog. When I log in I want the home screen to display a list of all new unapproved comments, as well as a list of recently registered users, and a list of the most recently submitted blog posts.

我见过的大多数讨论都表明强键入查看页面,因此可以用类似被称为返回视图(RecentComments),并通过在视图中评论迭代,或投像变种newusers使用的数据模型=(MembershipUserCollection)ViewData.Model。什么,我的理想就是以后的权利,或者至少是右足够的',传递多个型号,同时仍保持适当的逻辑分离的方式。

Most discussions I've seen suggest strongly-typing the view page so it can be called with something like "return View(RecentComments)" and iterate through the comments in the view, or to cast the data model like "var NewUsers = (MembershipUserCollection) ViewData.Model". What I'm ideally after is the 'right', or at least a 'right-enough', way of passing multiple models while still maintaining appropriate logic separation.

推荐答案

的一种方法是创建一个新类型,封装模型数据两部分组成:

One way is to create a new type that encapsulates both pieces of model data:

public class MyBigViewData {
    public SubData1 SubData1 { get; set; }
    public SubData2 SubData2 { get; set; }
}

public class SubData1 {
    ... more properties here ...
}

public class SubData2 {
    ... more properties here ...
}

的另一种方式是存储作为强类型数据中的主模式数据,并在视图中的数据的其他数据存储为字典项目:

Another way is to store the "main" model data as the strongly-typed data and store other data in the view data as dictionary items:

ViewData["username"] = "joe"; // "other" data
ViewData["something"] = "whatever"; // "other" data
ViewData["subdata1"] = new SubData1(...);
return View(myRealModelData);

第二个方法的优点是,你不需要做什么特别可言:它的工作原理正确的开箱即用

The advantage of the second approach is that you don't need to do anything special at all: It works right out of the box.

这篇关于发送到单个视图实例多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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