MVC~在Views的多级文件夹

来源:互联网 发布:炫知传播力分析系统 编辑:程序博客网 时间:2024/06/09 17:55

在MVC里,你的控制器对应的视图一般是在Views目录,而如果希望在Views里再分几个模块文件夹默认是不允许的,我们需要做一下设置,就可以实现Views下的多次文件夹层次了,例如,我们有产品模块,用户模块,订单模块,我们就可以把它的文件夹结构设计成如下

用户模块:/views/UserModel/UserCenter/Index,其中UserModel是模块名称,usercenter是控制器名称,而index是action名称

产品模块:/views/ProductModel/Product/Index

订单模块:/views/OrderModel/Order/Do

如果我们希望实现这种方式的视图,我们需要配置如下代码

1 建立你的路由

复制代码
   /// <summary>    /// 后台路由    /// </summary>    public class admin_routing : RazorViewEngine    {        public admin_routing()        {            ViewLocationFormats = new[]            {              "~/Views/{1}/{0}.cshtml",                "~/Views/Admin/{1}/{0}.cshtml"//自定义汽车销售的试图            };        }        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)        {            return base.FindView(controllerContext, viewName, masterName, useCache);        }    }
复制代码

2 配置你的路由,可以写下默认路由的下面

复制代码
  public class RouteConfig    {        public static void RegisterRoutes(RouteCollection routes)        {            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");            routes.MapRoute(                name: "Default",                url: "{controller}/{action}/{id}",                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }            );            routes.MapRoute(               "Admin", // 路由名称,这个只要保证在路由集合中唯一即可               "Admin/{controller}/{action}/{id}",                new { controller = "WebUser", action = "Index", id = UrlParameter.Optional } //            );        }    }
复制代码

3在global里添加视图引擎,并添加自定义的路由

     protected void RegisterView_Custom_routing()        {            ViewEngines.Engines.Clear();            ViewEngines.Engines.Add(new admin_routing());        }
复制代码
  protected void Application_Start()        {            AreaRegistration.RegisterAllAreas();            WebApiConfig.Register(GlobalConfiguration.Configuration);            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);            RouteConfig.RegisterRoutes(RouteTable.Routes);            BundleConfig.RegisterBundles(BundleTable.Bundles);            AuthConfig.RegisterAuth();            RegisterView_Custom_routing();        }
复制代码

最后,运行我们的webUser/Index地址,就可以看到想要的结果了

目录结果如下

阅读全文
0 0
原创粉丝点击