3

I ask a similar question here, I need to keep current URL and add new parameter to it, the only answer (yet) is :

RouteValueDictionary rt = new RouteValueDictionary();
foreach(string item in Request.QueryString.AllKeys)
  rt.Add(item,    Request.QueryString.GetValues(item).FirstOrDefault());

rt.Add("RC", RowCount);
return RedirectToAction("Index", rt);

So is there any other way to avoid of repetition over Request.QueryString and just get current url and add new parameter?

Community
  • 1
  • 1
Saeid
  • 13,224
  • 32
  • 107
  • 173

1 Answers1

3

you don't need to iterate the collection... you could simply append your parameters to the request's RawUrl:

    public ActionResult TestCurrentUrl(string foo)
    {
        var request = ControllerContext.HttpContext.Request;

        if (foo != "bar")
        {
            var url = request.RawUrl;

            if (request.QueryString.Count == 0)
            {
                url += "?foo=bar";
            }
            else
            {
                url += "&foo=bar";
            }

            return Redirect(url);
        }

        return Content(String.Format("Foo: {0}", foo));
    }
Ron DeFreitas
  • 629
  • 3
  • 12