在我的项目中,我有一个名为 Common
的文件夹,我想使用ASP.NET MVC搜索通用文件夹以查找视图,而不是共享文件夹。
换句话说,搜索位置的顺序视图如下:
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Common/Index.cshtml
~/Views/Common/Index.vbhtml
您可以创建自定义类RAZORVIEWENGINE
usin System.Web.Mvc
namespace Views.Infrastructure{
public class CustomrazorViewEngine : RazorViewEngin{
public CustomrazorViewEngine(){
ViewLocationFormats=new string[]{
"~/Views/{1}/{0}.cshtml",
"~/Views/Common/{0}.cshtml"
};
}
}
}
和global.asax
proteced void Application_Start()
{
AreaRegisteration.registerAllArea();
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new CustomrazorViewEngine());
RoutConfig.registerRoutes(RouteTable.Routes);
}
我建议这样做以防止其他引入的ViewEngines的封锁:
ViewEngines.Engines.Clear();
一个简单的解决方案。
在Application_Start
事件上,通过ViewEngines.Engines
收集RazorViewEngine
并更新其ViewLocationFormats
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().First();
razorEngine.ViewLocationFormats = new string[]
{
"~/Views/Home/Index.cshtml",
"~/Views/Home/Index.vbhtml",
"~/Views/Common/{0}.cshtml",
"~/Views/Common/{0}.vbhtml"
};
}
如果您只想更改订单,则可以使用Concat
方法将Defalut位置和新位置组合。
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().First();
var newLocationPath = new string[]
{
"~/Views/Home/Index.cshtml",
"~/Views/Home/Index.vbhtml",
"~/Views/Common/{0}.cshtml",
"~/Views/Common/{0}.vbhtml"
}.Concat(razorEngine.ViewLocationFormats);
razorEngine.ViewLocationFormats = newLocationPath.ToArray();
}