QueryString, Params, and Forms - Oh My!

Data can be passed between Web pages in a variety of ways. Know the differences and where each might be most useful.

Josef Finsel

October 30, 2009

7 Min Read
ITPro Today logo

ask asp.netNOW

 

LANGUAGES:C#

TECHNOLOGIES:Caching

 

QueryString, Params, and Forms - Oh My!

Data can be passed between Web pages in a variety ofways. Know the differences and where each might be most useful.

 

By Josef Finsel

 

I've encounteredmany different examples on the Web that read data from a Web form. Sometimesthey use QueryString, sometimes theyuse Params, and sometimes they use Forms. Which is correct?

- BR from Dayton,Ohio

 

To understand the differences between these, you firstneed to understand the two main methods used for transporting Web form dataacross the Web: POST and GET. To demonstrate this, I'll usethree Web forms: Get.aspx, Post.aspx, and Receiver.aspx. GET and POST will bothcontain Web forms that post to Receiverbut will use the two different methods of transporting data.

 

To being with, create the three forms and then openGet.aspx. Change the Document PageLayoutproperty to FlowLayout and add thesethree HTML controls (not Web Forms controls): A textbox for storing the user'sname, a submit button, and a hidden field with the value of HiddenText. Becausewe're not going to manipulate these objects programmatically, they simply needto have names so the data will be passed along. Now there's one last thing youneed to do before you're ready to use this form - modify the form's properties.

 

Every Web form includes a tag that defaults to posting the form back to itself.When you're finished, the HTML code should look like this:

 

  

   Please enter yourname:   

   

   

  

  

         type="hidden" value="HiddenData">   

 

The first thing to note is that you have modified thedefault method of POST to be GET, which makes this a good time to talk aboutthe differences between the two. Whenever you use a form on a Web page, itneeds to pass the named values (txtNameand txtHiddenData being the two youare passing in this form) to whatever page is going to process the data. The GET method passes the named values aspart of the URL. When I run this from my machine, enter data in the textbox,and submit, I get this URL:

 

http://localserver/DataInput/Receiver.aspx?txtName=jjf&txtHiddenData=HiddenData

 

The question mark (?) indicates the URL contains data.Each named value has the name to the left of the equals (=) sign and the valueto the right, and multiple values are separated with an ampersand (&). Aquick look at the previous URL shows one of the drawbacks to using the GET method: The URL includes all thedata and the hidden field isn't very hidden. For this reason, it's good not touse GET when using passwords andsuch. The other limitation of this way of passing data is that the amount ofdata you can send needs to fit in the Web browser's address window, and theserver must be able to process long URLs. Getting beyond 1,024 characters makesit more difficult to use the GETmethod of passing data.

 

But it the GETmethod does have advantages. For instance, the following link generates arandom quote as a graphic image using the QueryStringformat to determine the font, size, etc., that goes into the quote. This makesthe image much more flexible than it would be if you had to create separate.aspx files for each type of quote and have people link to them. The followinglink creates the image underneath it, and every time you refresh this page anew quote comes up. Give it a try:

 

http://www.reluctantdba.com/QuoteImage.aspx?font=Times%20New%20Roman&fontsize=14&width=80&Bold=True&bColor=MidnightBlue&fColor=White"eid=1

 

Now that we've looked at GET and its usefulness and limitations, it's time to take a quicklook at the POST form. The onlydifference between Post.aspx and Get.aspx is the form's method changes from GET to POST. Everything else stays the same, but this changes way the datais passed to the server. Instead of appending the named values to the URL, theyare put into the headers sent to the server. This not only makes the valuesmore secure by keeping them out of the URL, you can post more data to theserver this way. It's also possible to pass Unicode data because the headersallow it; the URL, however, doesn't.

 

Now that we've got the pages to POST and GET, let's workon the one to demonstrate how to access the data we're sending. As I mentionedearlier, the data being passed between the forms is in the form of named valuepairs, much like the old dictionary object. The easiest way to access the datais through the NameValueCollectionclass. Here is the code for the QueryStringcollection, which is duplicated for the Formsand Params collections:

 

NameValueCollection colQS=Request.QueryString;

// If here's at least one named value

if (colQS.AllKeys.Length != 0)  

{

  //Loop through namedvalues, print name and value

  for(iLoop=0;iLoop  {      strOutput.Append("" + colQS.AllKeys[iLoop] +      " =" + colQS.GetValues(iLoop).GetValue(0)       + "
");    }}else // No data available{  strOutput.Append("No QueryString Data Available"); }   The first step is to create a NameValueCollection and set it equal to the Request.QueryString object. The two main parts of the NameValueCollection you need are AllKeys (the names) and GetValues (the values associated withthose names). Using AllKeys.Lengthallows you to determine whether there are any name-value pairs. If so, you canloop through the pairs and print the name of the value from AllKeys and the value from GetValue(0). Now you're only passing insingle values, so you can use GetValue(0),but it is possible to have variables with the same name. This creates an arrayof values you'd need to loop through using a second counter. Finally, youappend this data to a StringBuilderobject so you can post it through a literal object on the Web form.   Although this code handles QueryString, Form, and Params the same way, this is a goodtime to talk about the difference between Paramsand the other two. The Params objectgrants you access to the named value without knowing where it is. In classicASP, it was common to write a function stored in an include file for accessing form data. This function lookedsomething like this:   'Purpose : Retrieve values from the POST or'GET Method (GET HAS PRIORITY) Function RequestForm(sRequestName)    IF(notISEmpty(Request.QueryString(sRequestName))) THEN      RequestForm =Request.QueryString(sRequestName)    ELSE      RequestForm =Request.Form(sRequestName)    END IFEnd Function   The Paramsobject works the same way, except it also includes the Cookie and Headerobjects as well, which leads to an important question based on the comment inthe previous code snippet: If you somehow have a same-named variable in both QueryString and the form, which oneshows up in the Params object? Tofind out, let's make a modification to the FORMtag in Post.aspx and add to it a QueryString variable called txtHiddenText with a value differentfrom the one in the form:  

 

Save the page, bring it up in the browser, submit it, andwhat do you get? Surprisingly enough, you get QSHiddenData, but not HiddenData.Does this mean the named variable from the POSTform is gone? Nope. Remember when I said we were looking only at GetValue(0)? That code won't work here.Because the variables have the same name, they stored under one key in a stringarray. Unfortunately, there is no way to tell which member of the array camefrom POST and which came from GET.

 

So, as with many things in ASP.NET, there is no right orwrong way to access the data from a form. If you are sending the data through POST, you either can use the Form or Params object. If you are using GET, you can use either QueryStringor Params. If you have a busy Website, you're probably better off not using Paramsto cut down on the overhead.

 

As for whether you use POST or GET depends onwhether the data should appear in the URL. Passwords in the URL are generally abad idea, but if you are going to provide a dynamic Web page other people canlink to, GET is the way to go. POST is necessary if you want to hidethe data in the headers, have a lot of data, or want to use Unicode.

 

The file referenced in this article is available fordownload. If you want additional information on the Quote Image referencedabove go to http://www.reluctantdba.com/RandomQuoteImage.aspx.

 

Have a question? Send it to [email protected].

 

Josef Finsel is asoftware consultant with G.A. Sullivan, a global software development company.He has published a number of VB and SQL Server-related articles, and he isworking on the syntax for FizzBin.NET, a programming language that works theway programmers have always suspected. He also wrote The Handbook for Reluctant Database Administrators (Apress).

 

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like