在MVC中返回并使用多个模型 [英] returning and using multiple models in MVC

查看:76
本文介绍了在MVC中返回并使用多个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经能够成功地将模型返回到视图并以强类型显示方式显示结果.

I've been able to successfully return a model to a view and display the results in a strongly-typed fashion.

我从未见过返回多个模型的示例.我该怎么办?

I have never seen an example where multiple models get returned. How do I go about that?

我想控制器将具有以下内容:

I suppose the controller would have something like this:

return View(lemondb.Messages.Where(p => p.user == tmp_username).ToList(), lemondb.Lemons.Where(p => p.acidity >= 2).ToList());

MVC是否可以让您返回多个模型?

Does MVC let you return multiple models like that?

然后在视图中,该行位于文件顶部:

And then in the view I have this line at the top of the file:

@model IEnumerable<ElkDogTrader.Models.Message>

而且我经常在视图中调用模型".

And I frequently make calls to "model" in the view.

@foreach (var item in Model)

如果有2个模型,我该如何分别参考它们?

If there were 2 models, how would I refer to them separately?

是否可以在多个模型中使用?或者这就是为什么人们使用ViewBag和ViewData吗?

Is this possible with multiple models, or is this why people use ViewBag and ViewData?

推荐答案

您可以创建一个表示视图所需数据的自定义模型.

You can create a custom model representing the data needed for your view.

public class UserView
{
    public User User{get;set;}
    public List<Messages> Messages{get;set;}
}

然后

return View(new UserView(){ User = user, Messages = message});

在视图中:

Model.User;
Model.Messages;

ViewBag很有用,因为它是动态键入的,因此您可以直接引用其中的成员而无需强制转换.但是,您确实会在编译时丢失静态类型检查.

The ViewBag is useful because it is dynamically typed, so you can reference members in it directly without casting. You do, however, then lose static type checking at compile time.

如果您对视图数据类型有一个一次性的了解并且知道该类型,并且无论如何将在视图中进行强制转换,ViewData可能会很有用.有些人喜欢在某种程度上保持实际类型化视图的纯净,因为它仅代表主要模型,而另一些人则喜欢在编译时利用类型检查的优势,因此可以创建视图所需的自定义模型.

ViewData can be useful if you have a one-off on your view data types and know the type and will be doing a cast in the view anyway. Some people like to keep the actual typed view pure in a sense that it represents the primary model only, others like to take advantage of the type checking at compile time and therefore make custom models needed for the view.

这篇关于在MVC中返回并使用多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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