开发者

Custom MVC route: changing where the views for a controller are located

开发者 https://www.devze.com 2023-02-02 22:08 出处:网络
So I have a controller called EmployeeController, and all the Views are in /Employee. I\'d like to create a route so that the EmployeeController will use /Employees an开发者_开发技巧d /Employees/Add

So I have a controller called EmployeeController, and all the Views are in /Employee.

I'd like to create a route so that the EmployeeController will use /Employees an开发者_开发技巧d /Employees/Add instead of /Employee and /Employee/Add.

I keep finding articles about how to change the route to go to different actions, but I couldn't find any way to do this.


I think you're confusing Views with Routes. ASP.NET MVC relies a lot on convention, and in this example it takes the controller component of the route an applies it to find the controller. You can define a new route:

routes.MapRoute("Employees", "employees/{action}", new { 
    controller = "Employee",
    action = "Index" });


Actually, there are 2 different questions:

  • First one is about routes mapping and here I'd agree on simple solution suggested by Matthew Abbott and Bugai13.
  • Second one is about "Views" folder conventions and View files resolution. If you want some custom logic about that you may inherit ViewResult and change the way it finds the appropriate View file. You can also dive deeper into framework and tweak the way View is found and instantiated by creating your own IViewEngine or customizing one of those already existing.

It seems though, that all you need is first thing - just provide more specific route mappings with URL pattern like employees/{action} and you're done.


Why not just rename EmployeeController to EmployeesController? Then you don't have to mess with the route.

Of course you will then have to change your Views\Employee folder to Views\Employees as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消