Setting a query string in redirecttoaction in asp.net mvc

I need to make a redirecttoaction call in an asp.net mvc view with variable parameters retrieved from the view referrer page (grid state).

I have (in a hidden field) the contents of the query string (sometimes empty, sometimes with two parameters, etc.), so I am having problems creating an array of route values.

Are there any helpers that help me convert the query string to an array of route values? Something like:

 string querystring ="sortdir=asc&pag=5"; return RedirectToAction( "Index", ConvertToRouteArray(querystring)); 
+5
query-string asp.net-mvc asp.net-mvc-routing redirecttoaction
Aug 29 '12 at 14:33
source share
2 answers

To create a one-stop solution, convert your query into a dictionary and dictionary into a RouteValueDictionary dictionary.

 var parsed = HttpUtility.ParseQueryString(temp); Dictionary<string,object> querystringDic = parsed.AllKeys .ToDictionary(k => k, k => (object)parsed[k]); return RedirectToAction("Index", new RouteValueDictionary(querystringDic)); 
+8
Aug 29 '12 at 14:38
source share

One of the limitations of using RedirectToAction("actionName", {object with properties}) is that RedirectToAction () does not have an overload that accepts RedirectToAction(ActionResult(), {object with properties}) , so you have to use magic strings for the name actions (and possibly the name of the controller).

If you use the T4MVC library, it includes two freely used API methods ( AddRouteValue(...) and AddRouteValues(...) ), which allow you to easily add a single querystring parameter, all object properties or the entire Request.QueryString. You can call these methods either on your own ActionResult T4MVC objects, or directly on the RedirectToAction () method. Of course, T4MVC is getting rid of magic strings!

As an example: suppose you want to redirect to the login page for an unauthenticated request and pass the originally requested URL as a parameter to the query string so that you can go there after a successful login. Any of the following syntax examples will work:

 return RedirectToAction(MVC.Account.LogOn()).AddRouteValue(@"returnUrl", HttpUtility.UrlEncode(Request.RawUrl)); 

or

 return RedirectToAction(MVC.Account.LogOn().AddRouteValue(@"returnUrl", HttpUtility.UrlEncode(Request.RawUrl))); 
+2
Jan 10 '13 at 20:10
source share



All Articles