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.
No. You should not do any DAL actions inside a view. I actually would recommend to only use
if
,foreach
and similar statements. Nothing else. Prepare your data in your controller and pass it in.You should put
new Webshop.DAL.ShopContext().Categories.ToList()
into your model that is used in the main view, and pass that to the partial view.You might need a
foreach
if you want to render the data in a list.If you want to do this for every page, you should create a new action, and let that action render, instead of a partial view. (That action should call the partial view). That action can acquire the required information and pass that onto the view.
Another approach is to return the partial view from your controller. Your controller action will be responsible for loading the model into the partial view. Your controller code will look something like this:
Now, you've got a loaded-up partial view.
What you can do is to use Html.Action or Html.RenderAction. This avoid call any DAL from View. You controller most have the action annotated as ChildActionOnly, and inside the action, like above answer comment, use return PartialView.
Use child actions.
ShopController.cs
_CategoryList.cshtml
_Layout.cshtml