2
\$\begingroup\$

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")
 .ToList();
 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);
 }
asked Jun 1, 2011 at 15:18
\$\endgroup\$
2
  • \$\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\$ Commented Jun 1, 2011 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\$ Commented Jun 1, 2011 at 17:18

1 Answer 1

2
\$\begingroup\$

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);
 else
 newQuery = string.Format("Page={0}", currentPageNo);
answered Jun 17, 2011 at 15:46
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.