Can this code be improved? I'm avoiding using the QueryString collection because the query string may contain eg: OrderBy=Column1&OrderBy=Column2 and it didn't seem helpful to start with those switched into QueryString["OrderBy"]=="Column1,Column2";

    var query = "";
    if (urlHelper.RequestContext.HttpContext.Request.Url != null)
        query = urlHelper.RequestContext.HttpContext.Request.Url.Query.TrimStart('?');
        if (query.Length > 0)
            var kvp =
                query.Split('&').Select(x => x.Split('='))
                    .Select(x => new { Key = x[0], Value = (x.Length > 0) ? x[1] : ""})
                    .Where(x => x.Key != "page")
            kvp.Add(new { Key = "page", Value = number.ToString() });
            query = String.Join("&", kvp.Select(x => x.Key + "=" + x.Value).ToArray());
        else query = String.Format("page={0}", number);
  • \$\begingroup\$ Why do you think it won't be helpful to switch to QueryString["OrderBy"]=="Column1,Column2". It seems to be more regular structure than several parameters with the same name. \$\endgroup\$ – Snowbear Jun 1 '11 at 16:39
  • \$\begingroup\$ The original query string comes from form data. MVC binds the multiple "OrderBy" as an IEnumerable<string>. If I convert the QueryString collection into a RouteValuesDictionary to recycle the query string the IEnumerable only has one value, and it breaks the view as a result. I guess it would be a valid suggestion to have the controller handle both cases gracefully. \$\endgroup\$ – mootinator Jun 1 '11 at 17:18

I think that yes this code can be improved.

use a regular expression:

            var newQuery = Regex.Replace(currentQuery, @"(?i)(page=\d*&?)", "").TrimEnd('&');
            if (newQuery.Length > 0)
                newQuery += string.Format("&Page={0}", currentPageNo);
                newQuery = string.Format("Page={0}", currentPageNo);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.