I frequently make use of Request.QueryString[]
variables.
In my Page_load
I often do things like:
int id = -1;
if (Request.QueryString["id"] != null) {
try
{
id = int.Parse(Request.QueryString["id"]);
}
catch
{
// deal with it
}
}
DoSomethingSpectacularNow(id);
It all seems a bit clunky and rubbish. How do you deal with your Request.QueryString[]
s?
Below is an extension method that will allow you to write code like this:
It makes use of
TypeDescriptor
to perform the conversion. Based on your needs, you could add an overload which takes a default value instead of throwing an exception:You can use the extension methods below as well and do like this
// Extension methods
Try this dude...
Then you will be able to search the guy for a string real easy via...
I do have functions for each (actually it's one small class, with lots of statics):
GetIntegerFromQuerystring(val)
GetIntegerFromPost(val)
....
It returns -1 if fails (which is almost always OK for me, I have some other functions for negative numbers as well).
Use int.TryParse instead to get rid of the try-catch block: