setting query string in redirecttoaction in asp.net mvc

Luca Morelli picture Luca Morelli · Aug 29, 2012 · Viewed 10.1k times · Source

I have to do a redirecttoaction call in asp.net mvc view with varying params, extracted from the referrer page of the view (the status of a grid).

I have (in an hidden field) the content of the query string (sometimes empty, sometimes with 2 parameters and so on), so I have problems to create the route values array.

Are there some helpers, that help me to convert a query string a route values array? Something like:

string querystring ="sortdir=asc&pag=5";
return RedirectToAction( "Index", ConvertToRouteArray(querystring));

Answer

Erwin picture Erwin · Aug 29, 2012

To create a generic solution convert your querystring to a Dictionary and at the dictionary to the RouteValueDictionary.

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

return RedirectToAction("Index", new RouteValueDictionary(querystringDic));