如何在ASP.NET MVC中使用部分视图?

编程入门 行业动态 更新时间:2024-10-24 10:15:12
本文介绍了如何在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.您的控制器中大多数操作的注释为 ChildActionOnly ,并且在操作内部(如上述答案注释一样)使用return PartialView.

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中使用部分视图?

本文发布于:2023-11-15 10:33:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1593652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   如何在   NET   ASP   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!