Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net webforms routing: optional parameters

I want to add optional parameters in my routing table. For example I would like the users to browse a product catalog like this: http://www.domain.com/browse/by-category/electronics/1,2,3 etc

Now i've created a route like this:

            routes.MapPageRoute(
           "ProductsBrowse",
            "browse/{BrowseBy}/{Category}",
            "~/Pages/Products/Browse.aspx"
        );

Problem however is that when a user enters http://www.domain.com/browse , I would like them to present a different page where they can pick the manner on how to browse. So the parameters {BrowseBy} and {Category} will not be used.

Is there a way around this then to create seperate routes for each of the scenarios?

Thank you for your time! Kind regards, Mark

like image 588
Mark Avatar asked Sep 23 '10 17:09

Mark


People also ask

How to make route parameter optional in. net Core?

We can make a route parameter optional by adding “?” to it. The only gimmick is while declaring a route parameter as optional, we must specify a consequent default value for it: [HttpGet("GetById/{id?}")] In this case, we assign 1 as a default value for the id parameter in the GetById action method.

How do I set optional parameters in Web API?

Optional Parameters in Web API Attribute Routing and Default Values: You can make a URI parameter as optional by adding a question mark (“?”) to the route parameter. If you make a route parameter as optional then you must specify a default value by using parameter = value for the method parameter.

Which is optional element when you define route config in Web API?

Web API uses URI as “DomainName/api/ControllerName/Id” by default where Id is the optional parameter. If we want to change the routing globally, then we have to change routing code in register Method in WebApiConfig.


2 Answers

I just came across this question, and knew there had to be way to do this. There is-

MapPageRoute has an overload that will allow you to specify defaults. here's an example usage based on your code:

routes.MapPageRoute(
       "ProductsBrowse",
        "browse/{BrowseBy}/{Category}",
        "~/Pages/Products/Browse.aspx",
        false,
        new RouteValueDictionary { { "Category", string.Empty } }
    );

So if the user doesn't specify a category this route will still be hit. The problem I have with using two separate routes is that I have links setup around my site that are generated by route name, and you cannot have two routes that have the same name.

Here's good documentation from MSDN: here

like image 90
The Muffin Man Avatar answered Nov 07 '22 06:11

The Muffin Man


try this:

routes.MapPageRoute(
           "ProductsBrowse",
            "browse/{BrowseBy}/{Category}/{*queryvalues}",
            "~/Pages/Products/Browse.aspx"
        );
like image 45
Azarsa Avatar answered Nov 07 '22 07:11

Azarsa