Haytam
Haytam

Reputation: 4733

Remove one query param value

Is it possible to remove 1 query param value in a simple way? (I'm thinking about recreating the list of values without the value we want to remove using RouteValueDictionary and IUrlHelper.ActionContext.HttpContext.Request.Query but I'm hoping there is a simpler way).

Example:

Original query: localhost:5555/search?cat=none&cat=cat1&cat=cat2

Wanted query (removing cat1): localhost:5555/search?cat=none&cat=cat2

Upvotes: 0

Views: 1445

Answers (1)

user47589
user47589

Reputation:

One way of doing this inside a controller's action method would be to do the following:

var queryParms = Request.GetQueryNameValuePairs();

GetQueryNameValuePairs is an extension method found in the System.Net.Http namespace.

queryParms is an IEnumerable<KeyValuePair<string, string>>. To filter it you can use some LINQ:

var queryParms = Request
    .GetQueryNameValuePairs()
    .Where(kvp => kvp.Key != "excluded key");

To filter by key/value pair:

var queryParms = Request
    .GetQueryNameValuePairs()
    .Where(kvp => kvp.Key != "excluded key" && kvp.Value != "excluded value");

This gives you a list of key/value pairs excluding the undesired query parameter. If you wanted to exclude a list of keys, you can use the following variation of the above:

var excludedKeys = new[] { "excluded a", "excluded b", "etc" };
var queryParms = Request
    .GetQueryNameValuePairs()
    .Where(kvp => !excludedKeys.Contains(kvp.Key));

If you need to change or replace a query parameter value:

var queryParms = Request.GetQueryNameValuePairs();
var cat = queryParms.FirstOrDefault(x=> x.Key == "cat");
if (cat != null && cat.Value == "cat1")
{
    cat.Value = "none";
}
// other stuff with query parms

Once you have your query parameters the way you want them, you'll need to reconstruct the URL. For this I turn you to a very good answer to another question:

https://stackoverflow.com/a/1877016/47589

Upvotes: 2

Related Questions