Best way to add parameter to the current URL in ASP.NET MVC3

4.6k Views Asked by At

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?

1

There are 1 best solutions below

0
On

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));
    }