如何在ASP.NET MVC中使用部分视图? [英] How to use Partial Views in ASP.NET MVC?

查看:61
本文介绍了如何在ASP.NET MVC中使用部分视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个ASP.NET MVC应用程序,并希望使用部分视图来显示我的产品类别.这将是一个网上商店,并且在菜单栏下方的每个页面上,我要显示另一个包含所有产品类别的栏.

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.

我想为此使用部分视图.当前在〜/Views/Categories 中,我创建了部分视图 _CategoriesHeader.cshtml .(我是通过在创建新视图"对话框中选择局部视图"来完成的,因此它实际上是局部视图)

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)

_CategoriesHeader.cshtml 的内容如下:

@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>

现在在〜/Views/Shared/_Layout.cshtml 中,我添加了以下代码:

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())

我想知道这是否是使用需要模型的局部视图的正确方法.现在,它只是内联创建一个新的DbContext对象以获取所有类别,但是我认为最好有一个模型.但是我不知道该怎么做.我在 Categories类别控制器.cs 具有用于此局部视图的方法的操作中,但是由于包含的视图已经加载了自己的模型,所以该方法不起作用.

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.

推荐答案

您可以使用Html.Action或Html.RenderAction.这样可以避免从View调用任何DAL.您的控制器中大多数操作的注释为

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.

这篇关于如何在ASP.NET MVC中使用部分视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆