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
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.
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).
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.
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 }));
The extension method seems correct and is the way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With