In ASP.net MVC I am using Url.RouteUrl & Html.RouteLink to create some links in my page.
Considering the following default route:
routes.MapRoute(
null,
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Using Url.RouteUrl(new { controller = "Products", action = "List", sort = "newest" }) will produce the URL /Products/List?sort=newest.
So far this is exactly what I want. What I’m not sure how to accomplish is the following. If I am currently on /Products/List?sort=newest. and I need to provide the user with a URL to change the number of products listed per page:
`/Products/List?sort=newest&pagesize=30`
How can I use Url.RouteUrl to generate the following URL so that:
- If I am currently on a page that has sort=newest, it retains this value: /Products/List?sort=newest&pagesize=30
- If I am currently on a page that doesn’t have sort, it omits it: /Products/List?pagesize=30
For an example of what I mean, you can look at stackoverflow. If I look at questions and change to view featured questions, and then click on the page size at the bottom it will retain the sorting but then append the page size to the URL.
If this is invoked from
/Products/Listit will produce/Products/List?pagesize=30. And if it is invoked from/Products/List?sort=newestit will produce/Products/List?sort=newest&pagesize=30.