我有两个模型类,每个都是数据库中的一个表。一种模型称为“衣服”,另一种模型称为“鞋子”。
我想在同一个 razor View 中显示每个表的内容,但 MVC 只允许我向 View 发送一个模型。
@model IEnumerable<Test.Models.Clothes>
有没有一种方法可以将多个模型发送到 Razor View ?
如果没有,在已传递另一个模型的 View 中显示另一个模型的内容的正常方法是什么。谢谢你的建议。
最佳答案
要么创建一个 View 模型类,该类将这两个类作为其对象。那么它将是类型安全的。
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 }
另一种简单的方法是使用 ViewBag。它使用 C# 4 中添加的动态功能。它允许对象动态添加属性。它也是类型安全的
ViewBag.Shoes= objShoes ;
ViewBag.Clothes= objClothes ;
您还可以使用 ViewData 将对象传递给 html。但这不是类型安全的。它需要类型转换
ViewData["Clothes "] = objClothes ;
ViewData["Shoes "] = objShoes ;
关于asp.net - 发送多个模型以查看 MVC 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11498399/