views:

175

answers:

2

I have multiple controllers with different actions (no "Index" actions). The actions I consider "default" actions, are named differently. I want to create default routes for their names and have the first available action (from my list of default actions) executed if only the controller name is provided in the route.

So, for example, I have the following actions which I want to consider default and want checked for their existence in a controller in this order:

List() 
Draw()
ViewSingle() 

The routing should somehow search for /{controller} and then take the first available action from the list above as default action, e.g.:

/ControllerA     -> ControllerA.List()
/ControllerB     -> ControllerB.Draw()
/ControllerC     -> ControllerC.ViewSingle()
/ControllerD     -> ControllerD.Draw()
/ControllerE     -> ControllerE.List()

Is this possible? I tried creating additional Default actions like this but couldn't get it to work:

routes.MapRoute("Default1", "{controller}/{action}", 
 new { controller = UrlParameter.Optional, action = "List" } 

routes.MapRoute("Default2", "{controller}/{action}", 
 new { controller = UrlParameter.Optional, action = "Draw" } 

routes.MapRoute("Default3", "{controller}/{action}", 
 new { controller = UrlParameter.Optional, action = "ViewSingle" } 

Help?

+1  A: 

I think you got something wrong about the default route. Those controller and action parameters are there for convention. If URL has a controller name in it, it will route to suitable controller. Same thing is true for Index methods. It just provides a default value for that.They are already optional and that's why. I think you don't need routes here: You could try to place your default functions in Index methods and it would work.Just to be clear:

public class ControllerA:Controller
{
    public ActionResult Index()
    {
        return List();
    }

    public ActionResult List()
    {
    //List function
    }
}


public class ControllerB:Controller
{
    public ActionResult Index()
    {
        return Draw();
    }

    public ActionResult Draw()
    {
    //Draw function
    }
}

I think it would work. But if you want to go on with creating routes, you create each route like this:

routes.MapRoute("Default1", "ControllerA", 
 new { controller = ControllerA, action = "List" }

Notice that ControllerA is not in curly braces,it's a static text. So you create routes for each controller. Keep controller naming convention in mind.

Ufuk Hacıoğulları
A: 

I agree with Narsil. You should write a constant to url. -like controller name- 'cause MVC cannot resolve this routes and cannot figure out what you want to show.

eg.

routes.MapRoute(null, "ControllerA/{action}", 
 new { controller = "ControllerA", action = "List" } 

routes.MapRoute(null, "ControllerB/{action}", 
 new { controller = "ControllerB", action = "Draw" } 

routes.MapRoute(null, "ControllerC/{action}", 
 new { controller = "ControllerC", action = "ViewSingle" } 
cem