I have a partial view for displaying a list of items, I use this partial view in several different places. Inside this partial view I use a paginator –
@Html.PagedListPager(Model, page => Url.Action(null, new { page = page }))
This results in the paginator showing page urls for whatever Action and View i’m already looking at.
Problem is, on my search page I use a query string for the search string, and the Url.Action method does not include existing querystring parameters.
Instead of /Search?s=bla&page=3 I end up with /Search?page=3
How can I generate a url using the existing query string?
Edit:
Here is my code
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(
"Search",
new SearchRoute("Search", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(
new { controller = "Search", action = "Index" })
});
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Call", action = "Index", id = UrlParameter.Optional }
);
}
public class SearchRoute : Route
{
public SearchRoute(string url, IRouteHandler routeHandler)
: base(url, routeHandler)
{
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
System.Diagnostics.Debug.WriteLine(Url);
if (HttpContext.Current != null)
{
string s = HttpContext.Current.Request.QueryString["s"];
if (!string.IsNullOrEmpty(s))
values.Add("s", s);
}
return base.GetVirtualPath(requestContext, values);
}
}
Using a custom route, you can preserve the query string because most Url generation logic uses the route to generate the URL. In this case I am checking the Request object for a query string called XXX and adding it into the route if it exists, you can make it more generic if you like.
Register the route as per normal in the global.ascx (though probably not for such a generic match as I have below)
Edit:
Ok, here’s an update.. its a bug fix, and an example of how to register the route (See corrected code above for bug fix)
Here’s how to register it: