I'm building an ASP.NET MVC application and want to use a partial view to display my product-categories. It is going to be a webshop and on each page, below the menubar, I want to show another bar which contains all product-categories.
I want to use a partial view for this. Currently in ~/Views/Categories I created the partial view _CategoriesHeader.cshtml. (I did that by selecting "Partial View" on the "Create New View" dialog, so it's actually a partial view)
The contents of _CategoriesHeader.cshtml are the following:
@model IEnumerable<Webshop.Models.Category>
@{
Layout = null;
}
<ul>
@foreach (var category in Model)
{
<li>@Html.ActionLink(category.Name, "Category", "Categories", new { ID = category.CategoryID }, null)</li>
}
</ul>
Now in ~/Views/Shared/_Layout.cshtml I added the following piece of code:
@Html.Partial("~/Views/Categories/_CategoriesHeader.cshtml", new Webshop.DAL.ShopContext().Categories.ToList())
I am wondering if this is the right way to use partial views that require a model. Now it just inline creates a new DbContext object to get all the categories, but I think it's better to have a model.
But I don't know how to do this. I did something where the CategoriesController.cs had a method for this partial view, but that didn't work because the containing view already had its own model loaded.
DbContextin the view goes against the MVC pattern. You should change the model of the main View to be an object that contains all items for the view and any partials.