如何在同一视图中使用2个模型

时间:2013-06-17 17:49:34

标签: asp.net-mvc

我想使用2个模型model_1model_2(一个model_1,许多model_2)但在一个视图中我只能使用一个。

这是我的观点:

@model IEnumerable<ProjectFashion.Models.model_1>
@model IEnumerable<ProjectFashion.Models.model_2>
@{
    ViewBag.Title = "VMenu";
}
<ul>
    @foreach(var n in Model) {
        <li class="dir">
            <h6>@n.name</h6>
                <ul>
                      @*I WANT TO GET model_2 which belongs to model_1*@
                </ul>
        </li>        
    }
</ul>

和我的_Layout.cshtml:

<!--vmenu-->
@Html.Action("VMenu", "Layout")
<!--vmenu-->

和我的LayoutController.cs:

ShopContent db = new ShopContent();
public ActionResult VMenu() {
    return PartialView("_VMenu", db.model_1s);
}

我还使用model_3来包含model_1model_2,但@Html.Action("VMenu", "Layout")中出现了一些问题。 (我对我不完美的英语感到抱歉......)

2 个答案:

答案 0 :(得分:0)

model_1上是否有导航属性可以为您提供相关的model_2?如果是这样,那么您只需要在填写了导航模型_2的情况下传递model_1。您可以在示例行中将其引用为类似@n.model_2s.property的内容。

答案 1 :(得分:0)

你不想要这个:

@model IEnumerable<ProjectFashion.Models.model_1>
@model IEnumerable<ProjectFashion.Models.model_2>

你想要这个:

@model ProjectFashion.Models.SomeCustomModel

您的自定义模型可以像这样简单:

public class SomeCustomModel
{
    public IEnumerable<model_1> FirstModel { get; set; }
    public IEnumerable<model_2> SecondModel { get; set; }
}

(我无法想出更好的名字,你的模型名称并没有真正留下任何关于它们的线索。)

然后在您的控制器操作中,您将创建一个SomeCustomModel的实例,填充其字段,并将其返回到视图。一般而言,您正在创建的是一个“复合对象”,它只包含其他对象。

当然,这是假设您的模型彼此之间没有任何其他现有关系。 (同样,这些名字并没有提供任何线索。)如果他们这样做,也许有一个“父”对象已经有了“子”对象?也许model_1包含model_2类型的属性或model_2个实例的集合?

相关问题