How to pass Request.QueryString to Url.Action?

后端 未结 3 2062
长发绾君心
长发绾君心 2020-12-23 16:31

I\'m building an url using the method:

Url.Action(\"action\", \"controller\");

I like to pass the querystring for the current request into

3条回答
  •  再見小時候
    2020-12-23 17:25

    Here's my solution based on pwhe23's answer. I wanted to keep query string parameters through POST requests (due to a Mvc.Grid) and use just a single action for HTTP GET. CRUD actions are handled by a single page and modal dialogs inside (for insert/update/delete).

    So here's my Extension:

    public static class MvcExtensions
    {
        public static RouteValueDictionary ToRouteValues(this NameValueCollection col, Object obj = null)
        {
            var values = obj != null ? new RouteValueDictionary(obj) : new RouteValueDictionary();
    
            if (col == null) return values;
    
            foreach (string key in col)
            {
                //values passed in object are already in collection
                if (!values.ContainsKey(key)) values[key] = col[key];
            }
            return values;
        }
    }
    

    Usage in Controller (e.g. Edit action):

        [HttpPost]
        public ActionResult Edit(MyModel model)
        {
            // Some stuff
            return RedirectToAction("Index", Request.QueryString.ToRouteValues());
        }
    

    Form for edit generated in View (modal dialog is used):

     @using (Html.BeginForm("Edit", "SomeControllerName", Request.QueryString.ToRouteValues(), FormMethod.Post))
        {
            // Some stuff... e.g. dialog content
        }
    

提交回复
热议问题