发送多个模型以查看MVC 4

use*_*260 9 asp.net asp.net-mvc razor asp.net-mvc-3

我有两个模型类,每个类都是数据库中的一个表.一种型号称为"衣服",另一种称为"鞋子".

我想在同一个剃刀视图中显示每个表的内容,但MVC只允许我向视图发送一个模型.

@model IEnumerable<Test.Models.Clothes>
Run Code Online (Sandbox Code Playgroud)

有没有办法将多个模型发送到剃刀视图?

如果没有,在已经传递给另一个模型的视图中显示另一个模型的内容的正常方法是什么.谢谢你的建议.

Ana*_*and 11

要么创建一个以类为对象的视图模型类.那将是类型安全的.

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 }
Run Code Online (Sandbox Code Playgroud)

使用ViewBag.It的另一种简单方法是使用添加到C#4中的动态功能.它允许对象动态地添加属性.它也是Type Safe

ViewBag.Shoes= objShoes ;
ViewBag.Clothes= objClothes ;
Run Code Online (Sandbox Code Playgroud)

您还可以使用ViewData将对象传递给html.这不是类型安全的.它需要铸造

ViewData["Clothes "] = objClothes ;
ViewData["Shoes "] = objShoes ;
Run Code Online (Sandbox Code Playgroud)

  • View Model是首选方法. (3认同)