Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Request.QueryString to Url.Action?

I'm building an url using the method:

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

I like to pass the querystring for the current request into that url as well. Something like the following (but it doesn't work):

Url.Action("action", "controller", Request.QueryString); 

Converting the QueryString to routevalues is possible with the following extension:

    public static RouteValueDictionary ToRouteValues(this NameValueCollection queryString)     {         if (queryString.IsNull() || queryString.HasKeys() == false) return new RouteValueDictionary();          var routeValues = new RouteValueDictionary();         foreach (string key in queryString.AllKeys)             routeValues.Add(key, queryString[key]);          return routeValues;     } 

With the extension method the following does work:

Url.Action("action", "controller", Request.QueryString.ToRouteValues()); 

Is there an other better way ? Thx

like image 277
Linefeed Avatar asked Apr 28 '11 11:04

Linefeed


People also ask

How do I pass QueryString?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.

What is request QueryString ()?

The value of Request. QueryString(parameter) is an array of all of the values of parameter that occur in QUERY_STRING. You can determine the number of values of a parameter by calling Request. QueryString(parameter).

What is query string with example?

A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML, choosing the appearance of a page, or jumping to positions in multimedia content.


2 Answers

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 })); 
like image 187
pwhe23 Avatar answered Sep 19 '22 21:09

pwhe23


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

like image 41
Darin Dimitrov Avatar answered Sep 21 '22 21:09

Darin Dimitrov