Click here to Skip to main content
Email Password   helpLost your password?

An URL inside the Microsoft Internet Explorer Address bar

Introduction

(For the latest changes, please see the History section below)

If you are working with URLs from within ASP.NET you probably often need to read different URL parameters. E.g., you could read the value of the "name1" parameter out of the QueryString collection of your Page class (or, to be more precise, from the Request property of your Page class):

private void Page_Load(
    object sender, 
    System.EventArgs e )
{
    string value1 = Request.QueryString["name1"];
 
    // ... Further processing of the value1 variable ... 

}

In my projects I often need the ability to write URL parameters, e.g., for outputting a URL on a page or for redirecting to another page with the appropriate parameters. This article introduces a class QueryString which I wrote in order to simplify my life a little bit.

Some Examples

Before examining the QueryString class in more detail, first some examples of how to use it are shown.

Example 1 - Manipulate an attribute value

Create a QueryString and simply let itself fill with the parameters of the current page:

private void Page_Load(
    object sender, 
    System.EventArgs e )
{
    // Let the object fill itself 

    // with the parameters of the current page.

    QueryString qs = new QueryString();
 
    // Read a parameter from the QueryString object.

    string value1 = qs["name1"];
  
    // Write a value into the QueryString object.

    qs["name1"] = "This is a value";
  
    // Redirect with the current content of the QueryString object.

    // In this example, since the BeforeUrl property is not modified,

    // it will redirect to the current page itself, but with the

    // "name1" parameter set to the new value.

    Response.Redirect( qs.All, true );
}

As you can see, you can simply modify a parameter's value by assigning it to the appropriate parameter name by using the [] operator. The All property returns the complete URL that is stored inside the QueryString object including the latest (possibly modified) parameters.

Example 2 - Removing parameters

To remove a certain parameter from the QueryString object, call the RemoveParameter method, specifying the name of the parameter to remove:

private void Page_Load(
    object sender, 
    System.EventArgs e )
{
    // Let the object fill itself 

    // with the parameters of the current page.

    QueryString qs = new QueryString();
 
    // Read a parameter from the QueryString object.

    string value1 = qs["name1"];
  
    // Now remove the parameter.

    qs.RemoveParameter( "name1" );
   
    // This has the same effect as RemoveParameter() method:

    qs["name1"] = null;
  
    // ... Further processing of the value1 variable ... 

}

The Class in brief

The most common use of the class was already described in the previous section. It should be simple to use, n'est pas? Nevertheless, here is an (incomplete) overview of the most usable members:

Constructors

The following constructors exists.

Methods for reading from a given URL

By using the following methods, you can achieve similar results as with the constructors, but after the object is already constructed.

Miscellaneous operations

Use the following methods for further operations.

Miscellaneous properties

Use the following properties for accessing various values.

Conclusion

In this small article I've shown you a class that simplifies the reading and writing of URL parameter values. For me, this class is around about approximately two years and helped me saving a lot of coding time (well, at least a bit...). Hopefully it is useful for you, too.

For questions, comments and remarks, please use the commenting section at the bottom of this article.

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
AnswerA way to remove parameter-name hardcode.
valera.kolupaev
1:54 10 Dec '09  
It's a good idea to encapsulate query-string works in separate class, but you can go further and add compile-time type checking to your's urls. I have blogged about it here.
GeneralThanks
ColinBashBash
12:02 26 May '09  
Thanks, that's just what i needed.

if (Membership.ValidateUser(Request["u"], pass)) {
FormsAuthentication.SetAuthCookie(Request["u"], false);

string redirect = FormsAuthentication.GetRedirectUrl(Request["u"], false);
QueryString q = new QueryString(redirect);
q.RemoveParameter("p");
q.RemoveParameter("u");
Response.Redirect(q.All);
}

... ie: the incredibleness of q.RemoveParameter();
GeneralRe: Thanks
Uwe Keim
12:04 26 May '09  
Thanks for your feedback Smile. Glad you liked it!

My personal 24/7 webcam - Always live Wink
Zeta Test - Intuitive, competitive Test Management environment. Download now!
Zeta Producer Desktop CMS - Intuitive, completely easy-to-use. Download now!

QuestionCompatibility and optimizations
PeterB72
3:52 25 May '09  
Hi,

I know this is a very old class. Maybe better versions exist, but I haven't find them. Looking at your code I have a few remarks/questions:

* Why are you not using StringBuilder in the Make() routines?

* Microsoft's HttpRequest.QueryString property does NOT include the question mark ("?") as part of the querystring, while your code does. It would be great if this could be made compatible.

* Valid querystrings can contain parameters without value (example.html?q) and multiple parameters with the same name (example.html?q=1&q=2&q=3). Various routines in your code do not take this into account.

* Your code also munges the hash part of the URL (everything that comes after the "#" character, as in example.html?q=1#test).
GeneralGreat work
Shahedul Huq Khandkar
22:39 24 Jul '06  
Thanks for making my life easier.;)
GeneralRe: Great work
Uwe Keim
22:44 24 Jul '06  
Thanks for your feedback Smile.

Be sure to check out my ZetaLibNet [^] article which always contains the latest version of the QueryString class. (You can use it separately without requiring the whole library to load).

--
Try our Windows-based CMS: www.zeta-producer.com
See me working: www.magerquark.com

GeneralDo you have it in vb.net?
HamidTheProgrammer
7:55 20 Sep '05  
Hi:
This is exactly what I am looking for, but I couldn't use it since I am using vb.net/asp.net Sigh. Do you have the vb.net version?

HamidTheProgrammer
AnswerRe: Do you have it in vb.net?
Uwe Keim
9:18 20 Sep '05  
Thanks, Hamid!

You could simply create a C#-DLL with my class and then use this class from within VB.NET.

Everything will work then! I do this the same for me with code which is only available in VB.NET.

--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!


GeneralRe: Do you have it in vb.net?
Gavin Harriss
16:35 19 Feb '07  
Only 2 years too late replying, but for the benefit of others still seeking an answer to this question...

This does a good job: http://www.kamalpatel.net/ConvertCSharp2VB.aspx[^]

Though you'll have to remove all <summary></summary> etc. tags as the ASP.NET page throws an error as it thinks you're doing naughty things with the input form.

Gavin Harriss
Portfolio: gavinharriss.com


GeneralA better C# to VB.NET converter
Gavin Harriss
16:54 19 Feb '07  
Actually, this one's far more forgiving...
http://www.developerfusion.co.uk/utilities/convertcsharptovb.aspx[^]

Gavin Harriss
Portfolio: gavinharriss.com


GeneralPageMethods helps with URLs
Anonymous
15:00 17 May '05  
Interesting work. Those who want to go further with URL handling in ASP.NET, can take a look at PageMethods. PageMethods enables well-defined URLs using methods and attributes.
GeneralRe: PageMethods helps with URLs
Uwe Keim
19:30 17 May '05  
If you already do advertising, next time include the URL Wink

http://metasapiens.com/PageMethods/ [^]

--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!


Generalquerystring and postback
magister
4:54 11 May '05  
I like this and think it is useful, but I notice every time I pass querystring parameters back to the page I am on I loose my page states...ie. Page.IsPostBack is false...

It would be good to be able to pass parameters back to a page without having this happen in some cases.
GeneralRe: querystring and postback
Uwe Keim
19:25 11 May '05  
It could probably register itself somehow in the postback chain. E.g. by providing an extended version that is droppable as a user control on a form.

But then,my title "...a small class..." is no longer true Wink

So currently I have no need for this but the idea is very good. Thanks for the suggestion!

--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!


GeneralQuite a useful class, done something similar
Sam Collett
0:41 11 May '05  

I'm sure this is very helpful to many people. I have done something similar in July 2004 (with an update in September 2004), which I use extensively (mine only has two constructors - one with no paramater to get the current page, and one with a string - supply 'page.aspx' to set to another page with the current page parameters, or 'page.aspx?q=1&q2=4' to set new parameters).


Url Manipulation v2 (C#)

Url Manipulation (C#)

Edit:
New Version



GeneralRe: Quite a useful class, done something similar
Uwe Keim
0:58 11 May '05  
Great class you've done! Maybe I can merge some of your code into my class if it fits...

Thanks for sharing!

--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!


GeneralGreat work
Noman Nadeem
21:23 25 Apr '05  
Great work. I just wish I could've stumbled accross this article a month ago !

regards,
Noman Nadeem Sleepy
GeneralRe: Great work
Uwe Keim
2:29 28 Apr '05  
Thank you! Big Grin

--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!


GeneralHow to retrieve only the parameters ?
Johann Frot
6:42 6 Apr '05  
Hi,

your code is exactly (and even more) what I needed ! Thanks a lot. Big Grin

One question : I know how to retrieve the "base" url --> member BeforeUrl
I also know how to get the whole Url --> member All

Is there a way to get only the parameters after the "?" ? I need this in order to pass them to an other page instead of the same one with the All.

thanks for your help

Johann
GeneralRe: How to retrieve only the parameters ?
Uwe Keim
18:00 6 Apr '05  
Thank you! Big Grin

You can use the Make() function to get the current contained parameters built as one ready-to-use string that contains only the parameters but including the "?".

So you could write:
string s = myQS.Make().TrimLeft( '?' );
if you want to get the parameters without the leading questionmark.

--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!


GeneralRe: How to retrieve only the parameters ?
Johann Frot
21:46 6 Apr '05  
Thanks, it works !
GeneralPerfect!
IPC2000
0:07 31 Mar '05  
Just what I needed. Thanks!
GeneralRe: Perfect!
Uwe Keim
1:05 31 Mar '05  
Thanks for your feedback! Good to hear that my work is actually being used Smile

--
Affordable Windows-based CMS: www.zeta-producer.com


GeneralValidation
Yussef
4:50 18 Jan '05  
First of all: Great class! I'm thinking of adding event driven validation to this class. The idea is that different controls (ASCX files) can hook to the validation event to check wether or not their variables are correct (not tampered with by the user or something like that).

Each control could call somthing like Querystring.IsValid to check wether or not the complete querystring is valid and decide to do a redirect or not.

I have to work this out, but what do you think of the idea? Smile
GeneralRe: Validation
Uwe Keim
18:25 18 Jan '05  
Nice idea, but probably to complicated/expensive in terms of performance.

Every of your controls could create a local instance of the class upon loading and check there directly...

--
Affordable Windows-based CMS: www.zeta-producer.com



Last Updated 6 Jan 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010