Search code examples
asp.net-mvc-3asp.net-mvc-routing

Routing does not work in my asp.net app


I have 4 routes defined 5 different urls. Tested a lot with RouteDebugger but can not solve.

The problem is that Top 2 links always use {controller}/{action}/{id} this route which is root1 and can not redirect to proper pages.

Links

@Html.ActionLink("Go Index by name", "Page", "Home", new { name="contact"}, null)

@Html.ActionLink("Go Index by id", "Index", "Admin", new { id=2}, null)


@Html.ActionLink("Go Index by id and name", "Page", "Home", new { name = "contact", id = 2 }, null)


@Html.ActionLink("Root Admin", "Index", "Admin")


@Html.ActionLink("Root", "Index", "Home")

Here is the Map.Route

    routes.MapRoute("root1",
      "{controller}/{action}/{id}",
       new { controller = "Admin", action = "Index" });

    routes.MapRoute("root2",
        "{controller}/{action}/{name}",
        new { controller = "Home", action = "Page" });

    routes.MapRoute("root3", 
        "{controller}/{action}/{name}/{id}", 
        new { controller = "Home", action = "Page" });

    routes.MapRoute("root4", 
        "{controller}/{action}/{name}", 
        new { controller = "Home", action = "Index", name = UrlParameter.Optional });

Solution

  • These are the routes I have set up and it seems to hit each one correctly.

    Note that root3 has been moved to the top since root2 will match that as well. also, the validation for root1 with id as King Julian suggested

    The route:

    @Html.ActionLink("Root Admin", "Index", "Admin")
    

    should not match root1 nor root2 since there is no default for id and name respectively in the route definition

    routes.MapRoute("root3",
         "{controller}/{action}/{name}/{id}",
          new { controller = "Home", action = "Page" });
    
    routes.MapRoute("root1",
          "{controller}/{action}/{id}",
          new { controller = "Admin", action = "Index" },
          new { id = @"\d+" });
    
    routes.MapRoute("root2",
          "{controller}/{action}/{name}",
          new { controller = "Home", action = "Page" });
    
    routes.MapRoute("root4",
          "{controller}/{action}/{name}",
          new { controller = "Home", action = "Index", name = UrlParameter.Optional     
    });