Search code examples
asp.netasp.net-mvcdictionaryredirecttoaction

Pass Dictionary<string,string> from POST to GET method (as url parameters) ASP.NET MVC


I have a problem. I'd like to pass a dictionary via RedirectToAction via RouteValueDictionary. Is there a possibility to do this?

I have a POST method:

[HttpPost]
public ActionResult Search(MyViewModel _myViewModel)
{
    IDictionary<string, string> parameters = new Dictionary<string, string>();

    foreach (var item in _myViewModel)
    {
        parameters.Add(item.ValueId, item.ValueName);   
    }

    return RedirectToAction("Search", new RouteValueDictionary(parameters));
}

I'd like to have an url like this:

http://localhost:26755/Searcher/Search?id1=value1&id2=value2&id3=value3

How the GET method should look like?

[HttpGet]
public ActionResult Search( **what's here?** )
{
    (...)
    return View(myViewModel);
}

Solution

  • First we need to fix your Search action that performs the redirect. You should use an IDictionary<string, object> instead of IDictionary<string, string> if you want to get the desired query string parameters when redirecting:

    [HttpPost]
    public ActionResult Search(MyViewModel _myViewModel)
    {
        IDictionary<string, object> parameters = new Dictionary<string, object>();
    
        foreach (var item in _myViewModel)
        {
            parameters.Add(item.ValueId, item.ValueName);   
        }
    
        return RedirectToAction("Search", new RouteValueDictionary(parameters));
    }
    

    and once you have done that in your target controller action you could just use the QueryString dictionary on the request:

    [HttpGet]
    public ActionResult Search()
    {
        // this.Request.QueryString is the dictionary you could use to access the
        // different keys and values being passed
        // For example:
        string value1 = this.Request.QueryString["id1"];
    
        ...
    
        // or you could loop through them depending on what exactly you are trying to achieve:
        foreach (string key in this.Request.QueryString.Keys)
        {
            string value = this.Request.QueryString[key];
            // do something with the value here
        }
    
        ...
    }