例如,您可以借助自定义视图引擎更改 Razor 搜索的视图文件位置。
通常,在 MVC 中,会在这些位置搜索部分视图:
// Part of the RazorViewEngine implementation from the Asp.net MVC source code
PartialViewLocationFormats = new[]
{
"~/Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.vbhtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.vbhtml"
};
然后添加例如LayoutsPartialViews
文件夹到Shared
文件夹并添加部分视图,例如仅用于布局。并添加例如ColorfuleHeader.cshtml
到那个位置。并尝试通过以下方式渲染该视图:
@Html.Partial("ColorfulHeader");
这样的异常会被抛出:
未找到部分视图“ColorfulHeader”或没有视图引擎
支持搜索位置。以下地点是
搜索...:
所以我们必须将此位置添加到搜索位置中。为此,我们必须创建自定义视图引擎:
public class CustomLocationViewEngine : RazorViewEngine
{
public CustomLocationViewEngine()
{
PartialViewLocationFormats = new[] {
"~/Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.vbhtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.vbhtml",
"~/Views/Shared/LayoutsPartialViews/{0}.cshtml",
"~/Views/Shared/LayoutsPartialViews/{0}.vbhtml",
};
}
}
另外,请记住,操作调用程序会依次访问每个视图引擎以查看是否可以找到视图。经过
当我们能够将视图添加到集合中时,它已经包含标准的 Razor 视图
引擎。为了避免与该实现竞争,我们称Clear
删除任何其他的方法
查看可能已经注册的引擎,然后调用Add
注册我们的自定义方法
执行。
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new CustomLocationViewEngine());