Search code examples
c#asp.net-mvcasp.net-mvc-5asp.net-mvc-routing

Routing to another action than Index as default


I already searched for long, but for this case I found no answer.

I have a HomeController and the default route in my route.config is as follows:

routes.MapRoute(
    name: "Default",  
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

So; http://localhost:36690/Home automatically calls Index.

I also have a MyController (and it's custom route in route.config) with an Index method and can just write http://localhost:36690/My and it works.

But I want to have a custom route without any Index.

If I request localhost:36690/New, it should call BASIC.

So I tried the following:

routes.MapRoute(
    "New",
    "{controller}/{action}",
    new { controller = "New", action = "Basic" }
);

But it ignores my default action 'Basic' and throws the error:

Server Error in '/' Application. The resource cannot be found. "


Solution

  • You can add another route specifically for that controller.

    routes.MapRoute(
        name: "New",
        url: "New/{action}",
        defaults: new { controller = "New", action = "Basic" }
    );
    
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    

    That way, when /New is called it will default to NewController.Basic