froggy
froggy

Reputation: 51

How to redirect some actions to another controller in mvc routes?

I have mvc actions defined in the controllers TasksController and TasksGridViewController. If the URL Tasks/Index or Tasks/GridView is called, MVC should look up the action in the TasksGridViewController, for all other actions it should use the TasksController.

I tried the following route for the action Index, but it doesn't work:

routes.MapRoute(
   name: "GridViewController/Index",
   url: "{controller}/Index",
   defaults: new
   {
       controller = "{controller}GridView",
       action = "Index"
   });

What am I doing wrong here? Thanks for any help.

Upvotes: 1

Views: 898

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

You could define those 2 specific routes BEFORE the default route:

routes.MapRoute(
    name: "GridViewController_Index_Action",
    url: "Tasks/Index",
    defaults: new
    {
        controller = "TasksGridView",
        action = "Index"
    }
);

routes.MapRoute(
    name: "GridViewController_GridView_Action",
    url: "Tasks/GridView",
    defaults: new
    {
        controller = "TasksGridView",
        action = "GridView"
    }
);

// Now comes the default route:
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = "" }
);

Upvotes: 2

Related Questions