简体   繁体   中英

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

Beginner's Question: 2 tables on my db: Products, Categories. 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. So I tried this in _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'.

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.

Assuming you have a ViewModel like:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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