Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 864
Saeid Avatar asked Dec 04 '25 02:12

Saeid


1 Answers

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));
    }
like image 96
Ron DeFreitas Avatar answered Dec 06 '25 16:12

Ron DeFreitas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!