简体   繁体   English

发送多个模型以查看MVC 4

[英]Sending more than one model to view MVC 4

I have two model classes, each is a table in a database. 我有两个模型类,每个类都是数据库中的一个表。 One model is called 'Clothes' and the other 'Shoes'. 一种型号称为“衣服”,另一种称为“鞋子”。

I want to display the contents of each table in the same razor view, but MVC is only letting me send one model to the view. 我想在同一个剃刀视图中显示每个表的内容,但MVC只允许我将一个模型发送到视图。

@model IEnumerable<Test.Models.Clothes>

Is there a way to send more than one model to a razor view? 有没有办法将多个模型发送到剃刀视图?

If not, what is the normal way to display contents of another model in a view that has already got another model passed to it. 如果没有,在已经传递给另一个模型的视图中显示另一个模型的内容的正常方法是什么。 Thanks for advice. 谢谢你的建议。

Either make a view model class which has both the class as its object. 要么创建一个以类为对象的视图模型类。 It would be then type safe. 那将是类型安全的。

public class ViewModelForDisplay
{
       public Clothes Clothes {get; set;}
       public Shoes Shoes {get; set;}
}

//on Controller
Clothes objClothes = GetClothes();
Shoes objShoes = GetShoes();

ViewModelForDisplay objViewModel = new ViewModelForDisplay() {Clothes = objClothes, Shoes= objShoes }

The other easy way to do it by using ViewBag.It uses the dynamic feature that was added in to C# 4. It allows an object to dynamically have properties added to it. 使用ViewBag.It的另一种简单方法是使用添加到C#4中的动态功能。它允许对象动态地添加属性。 Its also Type Safe 它也是Type Safe

ViewBag.Shoes= objShoes ;
ViewBag.Clothes= objClothes ;

You could also use ViewData to pass objects to html. 您还可以使用ViewData将对象传递给html。 BUt this would not be type safe. 这不是类型安全的。 It requires casting 它需要铸造

ViewData["Clothes "] = objClothes ;
ViewData["Shoes "] = objShoes ;

制作您自己的类,也就是查看模型,并让它由两个模型组成。

I have found this article very interesting : 我发现这篇文章非常有趣:

https://workspaces.codeproject.com/user-10826818/using-multiple-models-in-a-view-in-asp-net-mvc-4 https://workspaces.codeproject.com/user-10826818/using-multiple-models-in-a-view-in-asp-net-mvc-4

It presents different ways to send multiple models to a view : 它提供了将多个模型发送到视图的不同方法:

  • ViewData ViewData的
  • ViewBag ViewBag
  • PartialView PartialView
  • TempData TempData的
  • ViewModel 视图模型
  • Tuple 元组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM