ExtensionMethod.NET Home of 874 C#, Visual Basic, F# and Javascript extension methods

Modify Querystring

Modify the querystring of the current URL (or a passed in URL) to either add, update or remove parameters.

Source

public static class UrlHelperExtensions
{
	public static string ModifyQueryString(this UrlHelper helper, NameValueCollection updates, IEnumerable<string> removes)
	{
		return ModifyQueryString(helper, null, updates, removes);
	}

	public static string ModifyQueryString(this UrlHelper helper, string url, NameValueCollection updates, IEnumerable<string> removes)
	{
		NameValueCollection query;
		var request = helper.RequestContext.HttpContext.Request;

		if (string.IsNullOrWhiteSpace(url))
		{
			url = request.Url.AbsolutePath;
			query = HttpUtility.ParseQueryString(request.QueryString.ToString());
		}
		else
		{
			var urlParts = url.Split('?');
			url = urlParts[0];
			if (urlParts.Length > 1)
			{
				query = HttpUtility.ParseQueryString(urlParts[1]);
			}
			else
			{
				query = new NameValueCollection();
			}
		}

		updates = updates ?? new NameValueCollection();
		foreach (string key in updates.Keys)
		{
			query.Set(key, updates[key]);
		}

		removes = removes ?? new List<string>();
		foreach (string param in removes)
		{
			query.Remove(param);
		}

		if (query.HasKeys())
		{
			return string.Format("{0}?{1}", url, query.ToString());
		}
		else
		{
			return url;
		}
	}

	public static string UpdateQueryParam(this UrlHelper helper, string param, object value)
	{
		return ModifyQueryString(helper, new NameValueCollection { { param, value.ToString() } }, null);
	}

	public static string UpdateQueryParam(this UrlHelper helper, string url, string param, object value)
	{
		return ModifyQueryString(helper, url, new NameValueCollection { { param, value.ToString() } }, null);
	}

	public static string RemoveQueryParam(this UrlHelper helper, string param)
	{
		return ModifyQueryString(helper, null, new List<string> { param });
	}

	public static string UpdateQueryParams(this UrlHelper helper, NameValueCollection updates)
	{
		return ModifyQueryString(helper, updates, null);
	}

	public static string RemoveQueryParams(this UrlHelper helper, List<string> removes)
	{
		return ModifyQueryString(helper, null, removes);
	}
}

Example

Url.UpdateQueryParam("page", 4)

Url.RemoveQueryParam("q");

Author: Chris Pratt

Submitted on: 7 jul 2014

Language: C#

Type: UrlHelper

Views: 5935