将子目录添加到“查看/共享"ASP.Net MVC 中的文件夹并调用视图 [英] Adding sub-directory to "View/Shared" folder in ASP.Net MVC and calling the view
问题描述
我目前正在使用 ASP.Net MVC3 和 Razor 开发一个站点.在View/Shared"文件夹中,我想添加一个名为Partials"的子文件夹,我可以在其中放置我所有的部分视图(为了更好地组织站点.
I'm currently developing a site using ASP.Net MVC3 with Razor. Inside the "View/Shared" folder, I want to add a subfolder called "Partials" where I can place all of my partial views (for the sake of organizing the site better.
只要我在调用视图时始终引用Partials"文件夹(使用 Razor),我就可以毫无问题地做到这一点:
I can do this without a problem as long as I always reference the "Partials" folder when calling the views (using Razor):
@Html.Partial("Partials/{ViewName}")
我的问题是,是否有办法将Partials"文件夹添加到 .Net 在搜索视图时经过的列表,这样我就可以调用我的视图而无需引用Partials"文件夹,例如所以:
My question is if there is a way to add the "Partials" folder to the list that .Net goes through when searching for a view, this way I can call my view without having to reference the "Partials" folder, like so:
@Html.Partial("{ViewName}")
感谢您的帮助!
推荐答案
解决了这个问题.要将我创建的共享/部分"子目录添加到尝试在 Razor 中使用以下方法定位部分视图时搜索的位置列表:
Solved this. To add the "Shared/Partials" sub directory I created to the list of locations searched when trying to locate a Partial View in Razor using:
@Html.Partial("{NameOfView}")
首先创建一个以 RazorViewEngine 为基类的视图引擎,并添加你的视图位置,如下所示.同样,我想将所有部分视图存储在我在 MVC 创建的默认Views/Shared"目录中创建的Partials"子目录中.
First create a view engine with RazorViewEngine as its base class and add your view locations as follows. Again, I wanted to store all of my partial views in a "Partials" subdirectory that I created within the default "Views/Shared" directory created by MVC.
public class RDDBViewEngine : RazorViewEngine
{
private static readonly string[] NewPartialViewFormats =
{
"~/Views/{1}/Partials/{0}.cshtml",
"~/Views/Shared/Partials/{0}.cshtml"
};
public RDDBViewEngine()
{
base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();
}
}
请注意,位置格式中的 {1} 是控制器名称,而 {0} 是视图名称.
Note that {1} in the location format is the Controller name and {0} is the name of the view.
然后将该视图引擎添加到 global.asax 中 Application_Start() 方法中的 MVC ViewEngines.Engines 集合:
Then add that view engine to the MVC ViewEngines.Engines Collection in the Application_Start() method in your global.asax:
ViewEngines.Engines.Add(new RDDBViewEngine());
这篇关于将子目录添加到“查看/共享"ASP.Net MVC 中的文件夹并调用视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!