asp.net webforms routing: optional parameters

∥☆過路亽.° 提交于 2019-12-17 19:34:03

问题


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


回答1:


I'd just create the separate route.

That said, you could define a custom RouteHandler that based on some convention you define, automatically send those special cases as if you had a different route.

Alternatively you could use the custom RouteHandler along with a convention, to avoid having to specify the specific page in your routes. That's the equivalent of what asp.net MVC does.




回答2:


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




回答3:


try this:

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


来源:https://stackoverflow.com/questions/3781092/asp-net-webforms-routing-optional-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!