views:

107

answers:

5

Asp.net has turned out to be alot easier to use than PHP (so far). However, I have been searching for a while and simply cannot figure this out. How do I get the variables that are contained in the url of my page (that originate from a form that had the method "GET") and utilize them?

For example, my page would be www.example.com/index.asp?somevariable=something

How would I get the value of somevariable?

+2  A: 

It's as easy as :

Request.QueryString["somevariable"]; // C#
Request.QueryString("somevariable") ' VB
ybo
Thank you for that. I honestly don't know how I missed it.
A: 

This is for ASPX c#:

NameValueCollection pColl = Request.Params;
if (pColl["somevariable"] != null)
{
    string yourvalue = pColl["somevariable"];
}
Kb
Thank you as well
+3  A: 

You can use what ybo stated, but it isn't complete (for VB at least). That alone could leave to a null reference exception being thrown. You want to cast (i.e. TryParse) the values, and handle any empty parameters that your expected to contain a value:

Dim itemId As Integer
Dim itemType as String

If Not Integer.TryParse(Request.QueryString("i").ToString, itemId) Then
    itemId = -1 ' Or whatever your default value is
Else
    ' Else not required. Variable itemId contains the value when Integer.TryParse returns True.
End If

itemType = Request.QueryString("t").ToString ' <-- ToString important here!
HardCode
thank you. I was having some trouble implementing the querystring. I left off the .ToString
Hi. TryParse is not a cast, it's a conversion. Trying to invoke ToString on Request.QueryString("xxx") is a bad idea because *that* could lead to a null reference exception. Using Convert class is a better choice.
ybo
Request.QueryString("whatever").ToString will return an empty string when the parameter has no value. If the parameter doesn't exist at all, you WANT an exception thrown, because it is highly likely a bug in the code, where a missing param doesn't necessarily have to mean a bug.
HardCode
A: 

Any decent HTTP framework or library or piece of software, script/native/managed/routed, can cook/break down/crack the URL components for you.

Request.QueryString is an ancient way of dealing with it. Look up Uri Template mechanisms or new MVC bits. You'll need it sooner or later.

rama-jka toti
A: 

NameValueCollection col1 = Request.Query; name=col1.GetValues("somevariable")[0].ToString();