MVC小系列(八)【改变Areas的FindView顺序】
一般项目比较大的话,会根据模块建立Areas,这样结构清晰,也有利于路由的部署,
1 Areas下有自己的_LayOut模板,而如果希望所有Areas都用公有的(~/Views/Shared)下的模板,可以改变Areas的FindView规则
当然首先这个取模板的顺序要知道:
如果这几个地方模板名称一样,则优先级是这样
"~/Areas/{2}/Views/{1}/{0}.cshtml";
"~/Areas/{2}/Views/shared/{0}.cshtml";
"~/Views/Shared/{0}.cshtml";
而如果要改变这样的顺序,可以通过ViewEngines类型下的Engines属性,它是一个ViewEngineCollection类型的集合,可以往里面放很多规则,它会以第一个为准,
而这些规则可以向路由规则一样在Global里进行注册
第一步:建立页面搜索引擎
1 //建立一个页面搜索引擎,按着自己希望的View定位顺序,默认情况下Areas区域的View查询时,先找自己的areas,然后找view/shared,可以改变它的顺序 2 public class CustomRazorViewEngine : RazorViewEngine 3 { 4 public CustomRazorViewEngine() 5 : base() 6 { 7 base.AreaMasterLocationFormats = new string[] 8 { 9 "~/Views/Shared/{0}.cshtml", 10 "~/Areas/{2}/Views/{1}/{0}.cshtml", 11 "~/Areas/{2}/Views/Shared/{0}.cshtml", 12 }; 13 base.AreaViewLocationFormats = new string[] 14 { 15 "~/Areas/{2}/Views/{1}/{0}.cshtml", 16 "~/Areas/{2}/Views/Shared/{0}.cshtml", 17 "~/Views/Shared/{0}.cshtml" 18 }; 19 base.AreaPartialViewLocationFormats = base.AreaViewLocationFormats; 20 } 21 }
第二步:在Global注册页面引擎
1 protected void Application_Start() 2 { 3 4 #region 注册页面引擎 5 ViewEngines.Engines.Clear(); 6 ViewEngines.Engines.Insert(0, new CustomRazorViewEngine()); 7 #endregion 8 //AreaRegistration.RegisterAllAreas(); 9 10 //WebApiConfig.Register(GlobalConfiguration.Configuration); 11 //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 12 //RouteConfig.RegisterRoutes(RouteTable.Routes); 13 //BundleConfig.RegisterBundles(BundleTable.Bundles); 14 //AuthConfig.RegisterAuth(); 15 16 17 }
这样后面页面的搜索会按这个引擎走下去