建立自己MyViewEngine类让他继承RazorViewEngine,之后在构造函数里面写入设置视图位置格式代码如下:
public class MyViewEngine : RazorViewEngine { public MyViewEngine() { ViewLocationFormats = new[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml", "~/Views/UserInfo/{1}/{0}.cshtml",//UserInfo为Controllers控制器下的文件夹 //可以一直往下添 "~/Views/Admin/{1}/{0}.cshtml"//Admin为Controllers控制器下的文件夹 //注:{1}表示Controller的名称,{0}表示视图名称 }; } //public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) //{ // return base.FindView(controllerContext, viewName, masterName, useCache); //} }
进入默认RouteConfig类里面添加路由配置添加如下代码:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "UserInfo", url: "UserInfo/{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "Admin", url: "Admin/{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }
在Global下的Application_Start注册你添加你的CustomViewEngine类代码如下:
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); RegisterView();//注册视图访问规则 } protected void RegisterView() { ViewEngines.Engines.Clear();//移除默认视图配置 ViewEngines.Engines.Add(new FirstMVC.Models.MyViewEngine());//注册自己编写的视图格式 } }
时间: 2024-12-29 23:24:05