Search code examples
c#asp.netroutesurl-routingquery-string

How can i use second routedata value if there is


I am using asp.net routing with one variable without problem but i want to use two variable and second variable is not must. It can be or it can't be.

Want to use routes:

products/{a}/{id}
services/{b}/{id}

In this case i must enter "a" variable and "id" variable to reach url. But i want to open url if there is no {id} varible like:

products/{a}
services/{b}

If i delete {id} from url in routing, the url above is working properly.

I have tried to add {*id} and opened but get conflict when you're opening pages. There is a solution i have found with {id?} but causes an routing error. Any suggestion?

MY SOLUTION:

I have added a new route to solve this problem. It's not the best but working. If you have much better solution with same route please share with us.

routes.MapPageRoute("Products", "products/{a}", "~/products.aspx");
routes.MapPageRoute("Services", "services/{b}", "~/services.aspx");
routes.MapPageRoute("Productsid", "products/{a}/{id}", "~/products.aspx");
routes.MapPageRoute("Servicesid", "services/{b}/{id}", "~/services.aspx");

Solution

  • May be you can make your {id} parameter optional by adding a rule:

        routes.MapPageRoute(
           routeName: "Products",
           routeUrl: "products/{a}/{id}",
           physicalFile: "~/products.aspx",
           checkPhysicalUrlAccess: true,
           defaults: new RouteValueDictionary(new {
           id = UrlParameter.Optional,
        });
    

    Here is more which can help your more to get to your idea.