将子目录添加到“视图/共享"ASP.Net MVC中的文件夹并调用视图 [英] Adding sub-directory to "View/Shared" folder in ASP.Net MVC and calling the view
问题描述
我目前正在使用带有Razor的ASP.Net MVC3开发站点.在查看/共享"文件夹中,我想添加一个名为"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.
只要在调用视图(使用Razor)时始终引用"Partials"文件夹,我就可以毫无问题地做到这一点:
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创建的默认视图/共享"目录中创建的部分"子目录中.
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屋!