Controllers and views in subfolders

懵懂的女人 提交于 2020-02-20 11:39:38

问题


I am developing a web application using ASP.NET MVC 4 and I would like to organize my controllers and views in the following way:

/Controller    
    /Admin
        /LessonController.cs
        /ExerciseController.cs    
    HomeController.cs

/Views
        /Admin
              /Lesson
                   /Index.cshtml
        /Home
              /Index.cshtml

I tried the following code to register routes but it does not work:

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(
                name: "Admin",
                url: "Admin/{controller}/action/{id}",
                defaults: new { controller = "Lesson", action = "Index", id = UrlParameter.Optional }
                );

        }

Do you have any advices?


回答1:


You could use areas, they are kind of designed for this type of segregation and will give you some sort of separation out of the box:

/Areas
     /Admin
         /Controllers
             /LessonController.cs
             /ExerciseController.cs    
         /Views
             /Lesson
                 /Index.cshtml
             /Exercise
                 /Index.cshtml
/Controllers    
    /HomeController.cs
/Views
    /Home
        /Index.cshtml

If you don't want to follow the standard conventions that are supported by ASP.NET MVC you will have to write and register a custom view engine.




回答2:


Swap your routes round so the admin one is above the default one, then restart the application.



来源:https://stackoverflow.com/questions/14368427/controllers-and-views-in-subfolders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!