asp.net-mvcroutesroutetable

ASP.NET MVC Routing two parameters with static string in between


This is my routing:

routes.MapRoute(null,
    "shelves/{id1}/products/{action}/{id2}",
    new { controller = "Products", action = "List", id1 = "", id2 = ""});

The thought is that you can do something like this:

http://server/shelves/23/products/edit/14

And be able to edit product 14 on shelf 23. Checking it with Route Debugger, the path matches the routing, but when I try to navigate to it with Route Debugger off, it shows me a HTTP 404 error. Does anybody know why this is happening?


Solution

  • Well, for starters, that id1="" line is going to be problematic, because you can't make something optional that's not at the end.

    I just tried it on my system, and it works just fine.

    This is the route:

    routes.MapRoute(
        "shelf-route",
        "shelves/{id1}/products/{action}/{id2}",
        new { controller = "Products", action = "List", id2 = "" }
    );
    

    This is the controller:

    public class ProductsController : Controller
    {
        public string List(string id1, string id2)
        {
            return String.Format("ID1 = {0}, ID2 = {1}", id1, id2);
        }
    }
    

    I tried URLs like:

    http://localhost:14314/shelves/23/products/list/14
    http://localhost:14314/shelves/23/products

    And they worked just fine.

    When you tried the URL with "edit" in it, did you remember to make an Edit action? If there's no Edit action, you'll get a 404.