.NET Zone
.NET Zone is brought to you in partnership with:
spacer spacer Douglas Rathbone
  • Bio
  • Website
  • @dougrathbone
  • spacer

Doug Rathbone is a software architect working in Ad land. He is passionate about software design and automation, and regularly contributes to a number of industry sites on these topics. Douglas is a DZone MVB and is not an employee of DZone and has posted 33 posts at DZone. You can read more from them at their website. View Full User Profile

Replacing Query String Elements in C# .NET and JavaScript

07.19.2012
spacer Email
Views: 1877
  • Tweet
  • spacer
This article is part of the DZone .NET Zone, which is brought to you in collaboration with the .NET community. Visit the .NET Zone for additional tutorials, videos, opinions, and other resources on this topic.

We Recommend These Resources

Developing .NET/C# Applications with VoltDB

Real-Time SQL Access to Salesforce.com Data

Java Enterprise Performance

The Java Evolution Mismatch: Why You Need a Better JVM

Getting Started with Apache Camel - 6/28/2012 - 10:00AM EST

While writing list navigation and search features in websites today there is a constant need to find/replace and play with query string elements, so that you can easily manipulate these mystical items while you’re carrying them around in your website’s URLs. I have a few little methods I’ve used over the years and carry with me project to project, and this post is putting them on the record for easy access later.

I have a secret. This post is actually more aimed at an audience of 'myself', and my ability to have an easy bit of source code to call upon when I’m on the go looking for a quick solution to cut and paste – as most of my blog posts are. But you, dear reader, you get to share in this benefit with me by pulling from the awesomeness within this post as well.

Solution: .Net c#

When doing this with c# you have a few pretty cool features up your sleeve. One of these is HttpUtility.ParseQueryString(urlPath) framework method. This static method allows you to extract a NameValueCollection that is editable from a given query string. Why is this cool? Because it allows you to very easily play with the query string collection like it is any other NameValueCollection – with Add() and Remove() methods. This makes it incredibly powerful.

Quick & Dirty code beware!

The code I’m pasting below is far from being the most elegant solution, i seem to have misplaced my nicer piece of code and am in too much of a rush to find it right now (sorry). Until i find my nicer solution, the method below will get you by – whether you have a hatred for ternary’s or not.

public static string ReplaceQueryStringParam(string currentPageUrl, string paramToReplace, string newValue)
{
    string urlWithoutQuery = currentPageUrl.IndexOf('?') >= 0 
        ? currentPageUrl.Substring(0, currentPageUrl.IndexOf('?')) 
        : currentPageUrl;

    string queryString = currentPageUrl.IndexOf('?') >= 0
        ? currentPageUrl.Substring(currentPageUrl.IndexOf('?')) 
        : null;

    var queryParamList = queryString != null 
        ? HttpUtility.ParseQueryString(queryString) 
        : HttpUtility.ParseQueryString(string.Empty);

    if (queryParamList[paramToReplace] != null)
    {
        queryParamList[paramToReplace] = newValue;
    }
    else
    {
        queryParamList.Add(paramToReplace, newValue);
    }
    return String.Format("{0}?{1}", urlWithoutQuery, queryParamList);
}

To call this, you can do the following:

// var currentUrl = HttpContext.Current.Request.Url;
var currentUrl = "www.mysite.com/mypage?category=cool-products&sort=price&page=3";

// change the my sort-by param named"sort" to "name"
var newUrlWithChangedSort = ReplaceQueryStringParam(currentUrl, "sort", "name");

Solution: JavaScript

The second part of this post includes a JavaScript solution, as you never know when you have to do this on the client side.

function replaceQueryString(url, param, value) 
{
    if (url.lastIndexOf('?') <= 0) url = url + "?";

    var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
    if (url.match(re))
        return url.replace(re, '$1' + param + "=" + value + '$2');
    else
        return url.substring(url.length - 1) == '?'
            ? url + param + "=" + value 
            : url + '&' + param + "=" + value;
}

And to use the above code in your client-side javascript simply write something along the lines of:

//var currentUrl = self.location;
var currentUrl = "www.mysite.com/mypage?category=cool-products&sort=price&page=3";

// change the my sort-by param named"sort" to "name"
var newUrlWithChangedSort = replaceQueryString(currentUrl, "sort", "name");

Easy – now next time you need to knock something together, instead of writing it yourself, you can simply cut & paste mine!

Published at DZone with permission of Douglas Rathbone, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:
  • Tutorial
  • C-Sharp
  • Javascript
This content was brought to you by DZone for all the information you need on ASP.NET, WPF, XAML, SQL Server, and other pieces of the .NET stack.