简体   繁体   English

如何在PartialView中创建模型的foreach循环? (MVC.NET)

[英]How to create foreach loop of a Model in a PartialView? (MVC.NET)

Beginner's Question: 2 tables on my db: Products, Categories. 初学者的问题:在我的数据库上有2个表:产品,类别。 I created a View of Products. 我创建了一个产品视图。 And I have a Sidebar Menu as a Partial View. 我有一个侧边栏菜单作为局部视图。

PartialView Name: _SidebarMenu
Layout Name:      _AdminLayout

I want to list my categories in _SidebarMenu dynamically. 我想在_SidebarMenu中动态列出我的类别。 So I tried this in _SidebarMenu: 所以我在_SidebarMenu中尝试了这个:

@model IEnumerable<ProjectName.MVCWebUI.Models.Categories>

@foreach (var item in Model)
     {
        <li><a href="#">@item.CategoryName</a></li>
     }

But I got a Server Error: 但我收到服务器错误:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1 [ProjectName.MVCWebUI.Models.Products]', but this dictionary requires a model item of type 'ProjectName.MVCWebUI.Areas.Admin.Models.AdminMenuContent'. 传递到字典中的模型项的类型为'System.Collections.Generic.List`1 [ProjectName.MVCWebUI.Models.Products]',但是此字典需要模型项的类型为'ProjectName.MVCWebUI.Areas.Admin.Models .AdminMenuContent”。

How can I list a different Model rather than a Model in a rendering View? 如何在渲染视图中列出其他模型而不是模型?

I would recommend using a child action, since it's virtually impossible to ensure that the right model will be passed to the partial in every single view otherwise. 我建议使用子操作,因为实际上不可能确保将正确的模型传递给每个单独视图中的部分对象。 Basically, in the controller of your choice, add an action like: 基本上,在您选择的控制器中,添加一个类似以下的动作:

[ChildActionOnly]
public ActionResult SidebarMenu()
{
    // get categories from DB or whatever
    return PartialView("_SidebarMenu", categories);
}

Then, in your layout, add the following where you want this menu to appear: 然后,在您的布局中,将以下内容添加到希望此菜单出现的位置:

@Html.Action("SidebarMenu", "Foo")

Where "Foo" is the name of the controller you put this action in. 其中“ Foo”是您放置此操作的控制器的名称。

Assuming you have a ViewModel like: 假设您有一个ViewModel像:

public class IndexViewModel()
{
    public List<Product> Products { get; set; }
    public List<Category> Categories { get; set; }
}

Main view would have the: 主视图将具有:

@model IndexViewModel

Partial would have: 部分将具有:

@model List<Category>

So from your main view you could render the partial and passing the correct list like: 因此,从您的主视图中,您可以渲染部分内容并传递正确的列表,例如:

@Html.Partial("~/Areas/....your_partial_name.cshtml", Model.Categories)

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

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