MVC自定义视图引擎地址

时间:2022-05-04
本文章向大家介绍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());
        }  

效果图