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

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

问题描述

我的术语可能离这里很远,但基本上我正在尝试将多个数据模型传递给一个视图.为了帮助将问题置于上下文中,请看以下示例:

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)"之类的东西来调用它并遍历视图中的评论,或者将数据模型转换为var 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天全站免登陆