发送多个模型查看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'.
我想要在同一剃刀视图中显示的每个表中的内容,但MVC只让我发送一个模式向视图。
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.
@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 }
其他简单的方法使用ViewBag.It做它使用在为C#4中添加它允许一个对象动态有属性添加到它的动态特征。它也是类型安全的。
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. Its also Type Safe
ViewBag.Shoes= objShoes ;
ViewBag.Clothes= objClothes ;
您也可以使用的ViewData对象传递给HTML。但这不会是类型安全的。它要求铸造
You could also use ViewData to pass objects to html. BUt this would not be type safe. It requires casting
ViewData["Clothes "] = objClothes ;
ViewData["Shoes "] = objShoes ;
这篇关于发送多个模型查看MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!