实现Asp.Net Mvc4多级Views目录

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现Asp.Net Mvc4多级Views目录相关的知识,希望对你有一定的参考价值。

建立自己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());//注册自己编写的视图格式
    }
}

 

以上是关于实现Asp.Net Mvc4多级Views目录的主要内容,如果未能解决你的问题,请参考以下文章

ASP.Net MVC4排序检索分页的实现

翻译转载官方教程Asp.Net MVC4入门指南:添加一个控制器

ASP.NET MVC4入门到精通系列目录汇总(转)

ASP.NET MVC4入门到精通系列目录汇总

ASP.NET MVC4企业级实战目录

快速开发之代码生成器(asp.net mvc4 + easyui + knockoutjs)