MVC自定义视图引擎地址

先看结构

 

1、RouteConfig 文件(注意顺序)

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            
            routes.MapRoute(
               name: "Manage_Default",
               url: "Manage/{controller}/{action}/{id}",
               defaults: new { controller = "Demo", action = "Index", id = UrlParameter.Optional },
               namespaces: new string[] { "Ku_MVC.Controllers.Manage" }
           );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

  2、新增文件 MyRazorViewEngine

public class MyRazorViewEngine : RazorViewEngine
    {
        public MyRazorViewEngine()
            : base()
        {
            ViewLocationFormats = new[] {  
                 "~/Views/{1}/{0}.cshtml",
                 "~/Views/Manage/{1}/{0}.cshtml",
            };

        }

        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            return base.CreatePartialView(controllerContext, partialPath);
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            return base.CreateView(controllerContext, viewPath, masterPath);
        }

        protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
        {
            return base.FileExists(controllerContext, virtualPath);
        }
    }

  3、Global.asax 

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
             
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            RegisterView();
        }
        protected void RegisterView()
        {
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new Controllers.MyRazorViewEngine());
        }  

 

效果图

 

我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan

 

posted @ 2018-01-04 23:06  初吻给了糖  阅读(358)  评论(0编辑  收藏  举报