您可以编写一个custom view engine
可以指定 ASP.NET MVC 将在其中查找视图的其他文件夹的位置。
这里的想法是编写一个派生自RazorViewEngine
并在其构造函数中设置各种属性的类,例如:
- 区域视图位置格式
- AreaMasterLocationFormats
- AreaPartialViewLocationFormats
- 查看位置格式
- MasterLocation格式
- PartialViewLocationFormats
以下是您可以随意覆盖的默认值:
public RazorViewEngine(IViewPageActivator viewPageActivator) : base(viewPageActivator)
{
base.AreaViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/{1}/{0}.vbhtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.vbhtml" };
base.AreaMasterLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/{1}/{0}.vbhtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.vbhtml" };
base.AreaPartialViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/{1}/{0}.vbhtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.vbhtml" };
base.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml", "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml" };
base.MasterLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml", "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml" };
base.PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml", "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml" };
base.FileExtensions = new string[] { "cshtml", "vbhtml" };
}
然后只需在以下位置注册您的自定义视图引擎Application_Start
:
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MyRazorViewEngine());
在此示例中,我在注册自定义视图引擎之前删除了所有其他默认视图引擎(WebForms 和 Razor)。