Ankit Bansal
Ankit Bansal

Reputation: 79

Passing Query String in RedirectToAction MVC

I have splitted the Query String from the Original Url and want to pass it after changing the Culture of the application.

How can I pass the query string which I have extracted in the RedirectToAction method.

  public ActionResult Culture(string culture)
       {
           if (!string.IsNullOrEmpty(culture))
            {
               this.Response.Cookies[PagingExtensions.COOKIE_NAME].Value = culture;
           }
spliturl.split(System.Web.HttpContext.Current.Request.UrlReferrer.ToString());
//this would return the controller name and action name and the query string as string value.

  var parsed = HttpUtility.ParseQueryString(spliturl.queryString); 
        Dictionary<string,object> querystringDic = parsed.AllKeys.ToDictionary(k => k, k => (object)parsed[k]); 

        return RedirectToAction(spliturl.action, new RouteValueDictionary(querystringDic));

Can I do something like this to transfer the control to action with the following query string.

Upvotes: 0

Views: 3203

Answers (1)

gokkor
gokkor

Reputation: 809

This is (I think) all you need. The following code redirects user to another controller/action etc as per your needs (of course you need to adjust it as you need it)

            string controller = RouteData.Values.ContainsKey("controller") ? RouteData.Values["controller"].ToString() : "";
        string action = RouteData.Values.ContainsKey("action") ? RouteData.Values["action"].ToString() : "";
        string id = RouteData.Values.ContainsKey("id") ? RouteData.Values["id"].ToString() : ""; // maybe you have may be you dont?

        action = "Contact";  // to to avoid loop in my test application, remove this line if you need

        // this.Request.QueryString.AllKeys

        System.Web.Routing.RouteValueDictionary target = new System.Web.Routing.RouteValueDictionary();
        target.Add("controller", controller);
        target.Add("action", action);

        if (!string.IsNullOrWhiteSpace(id))
        {
            target.Add("id", id);
        }


        foreach(string key in Request.QueryString.AllKeys)
        {
            target.Add(key, Request.QueryString[key]);
        }

        return RedirectToRoute(target);

Upvotes: 1

Related Questions