问题
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