在RedirectToAction MVC中传递查询字符串

时间:2014-12-24 08:11:14

标签: asp.net asp.net-mvc redirect request

我已从原始网址中拆分查询字符串,并希望在更改应用程序的文化后传递它。

如何传递我在RedirectToAction方法中提取的查询字符串。

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

我是否可以使用以下查询字符串将控件转移到操作。

1 个答案:

答案 0 :(得分:1)

这是(我认为)您所需要的一切。以下代码根据您的需要将用户重定向到另一个控制器/操作等(当然您需要根据需要进行调整)

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