Search code examples
asp.netasp.net-mvcasp.net-mvc-routing

ASP.NET MVC Set default controller action


Please I need to be guided to set a default action for my controllers such that anytime there is no action indicated in a controller, the application will route to the index action on the given controller. For example, if someone navigates to dashboard/ without indicating the action, the application automatically runs the index action of the dashboard controller.

The following shows my attempts but it is still not working.

public class RouteConfig
{
  public static void RegisterRoutes(RouteCollection routes)
  {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
      routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
    );
    routes.MapRoute(
      name: "Regular",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
    );
    routes.MapRoute(
      name: "ControllerDefault",
      url: "{controller}",
      defaults: new {  action = "Index"}
    );
  }
}

I will appreciate any guide to get it working right,


Solution

  • you have to different route on the same url. you only need to use the default route.

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

    you can change "Home" to "Dashboard" if that is your default controller.