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?
The value of Request. QueryString(parameter) is an array of all of the values of parameter that occur in QUERY_STRING. You can determine the number of values of a parameter by calling Request. QueryString(parameter).
A Query String Collection is used to retrieve the variable values in the HTTP query string. If we want to transfer a large amount of data then we can't use the Request. QueryString. Query Strings are also generated by form submission or can be used by a user typing a query into the address bar of the browsers.
Check if a query string parameter existsThe URLSearchParams.has() method returns true if a parameter with a specified name exists.
Form, the Web server parses the HTTP request body and returns the specified data. If your application requires unparsed data from the form, you can access it by calling Request. Form without any parameters. The QueryString collection retrieves the values of the variables in the HTTP query string.
Below is an extension method that will allow you to write code like this:
int id = request.QueryString.GetValue<int>("id"); DateTime date = request.QueryString.GetValue<DateTime>("date");
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:
public static T GetValue<T>(this NameValueCollection collection, string key) { if(collection == null) { throw new ArgumentNullException("collection"); } var value = collection[key]; if(value == null) { throw new ArgumentOutOfRangeException("key"); } var converter = TypeDescriptor.GetConverter(typeof(T)); if(!converter.CanConvertFrom(typeof(string))) { throw new ArgumentException(String.Format("Cannot convert '{0}' to {1}", value, typeof(T))); } return (T) converter.ConvertFrom(value); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With