Since we need to manipulate HTTP request parameters frequently in ASP.NET MVC, I thought I’d share my experience of manipulating them. One scenario where you might need this functionality would be when we are building a new or updated URL based on the value of certain URL Query parameters sent in by a user – say we are creating a href attribute of the HTML a link tag.
One approach would be to encapsulate this logic in a ViewHelper method implemented as an extension method on HtmlHelper class. Next, we will need to create a clone of the NameValueCollection instance as the NameValueCollection instance we get by calling HttpRequestBase.QueryString is read-only, i.e. we can’t change or manipulate the query parameters in the collection or the collection itself.
Note the use of HttpUtility.ParseQueryString() method as it is key to our solution. This method takes a flattened string which contains query parameters in the form such as value1=hello&value2=world and returns a new instance of NameValueCollection that can be manipulated. Another sweet point of this method is that when we are finally ready to generate our updated Url as string we need not do any string manipulation. Our NameValueCollection instance automatically reformats this in the required querystring format.
For our scenario let’s say we have a URL as http://example.com/index.aspx?key1=value1&key2=&key3=value3 and we want to remove the query parameter with key key2 if it is empty. This is how we can implement the scenario in ASP.NET MVC 2.
public static class MyViewHelper
{
public static string GetUpdatedUrl(this HtmlHelper helper)
{
HttpRequestBase request = Helper.ViewContext.HttpContext.Request;
var queryParams = HttpUtility.ParseQueryString(request.Url.Query);
if(queryParams["key2"] == null)
queryParams.Remove("key2);
return request.Url.AbsolutePath + "?" + queryParams);
}
}
Now, we can use GetUpdatedUrl() in our ASP.NET MVC views like so,
Click Me