How to pass Request.QueryString to Url.Action?

后端 未结 3 2052
长发绾君心
长发绾君心 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:06

    If you want to easily be able to add additional route value parameters to your Url.Action, try this extension method (based on Linefeed's) which takes an anonymous object and returns a RouteValueCollection:

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

    Then you can use it like so:

    Url.Action("action", "controller", Request.QueryString.ToRouteValues(new{ id=0 }));
    
    0 讨论(0)
  • 2020-12-23 17:18

    The extension method seems correct and is the way to go.

    0 讨论(0)
  • 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
        }
    
    0 讨论(0)
提交回复
热议问题