by

Recently I was trying to update a query string by adding or updating a parameter for URLs generated in a partial view.

I found an excellent example for achieving this by setting route data here however this didn’t preserve current query string values in the URL. I’ve extended upon that code and updated it to include the query string values in the route data which will be appended to the query string in the generated URL (assuming the parameter key doesn’t match part of the route).

public static HtmlString RouteValueChange(this UrlHelper url, object routeValues)
{
    // Convert new route values to a dictionary
    RouteValueDictionary newRoute = new RouteValueDictionary(routeValues);
 
    // Get the route data of the current Url
    var current = url.RequestContext.RouteData.Values;
 
    // Merge the new values INTO the current route values, overwriting any existing values
    foreach (var item in newRoute)
    {
        current[item.Key] = item.Value;
    }
 
    // Merge the new values INTO the current querystring values, overwriting any existing values
    var queryString = url.RequestContext.HttpContext.Request.QueryString;
    foreach (var key in queryString.AllKeys)
    {
        if (!current.ContainsKey(key))
        {
            current.Add(key, queryString[key]);
        }
    }
 
    // Generate the new Url
    var newUrl = url.RouteUrl(current);
    return new HtmlString(newUrl);
}