Today, at my work I have to find a way on how to get the query string parameters and use them in logic. I mean, I can get them in javascript side and send them as parameters, but I don’t want to implement it that way as I have everything in query string, I can get it from URL and use it in server side code. And second thing is, the query string parameters are not plain text, they are encrypted with a strong algorithm. So, below is the small function I written which work perfect.
//Get Querystring name value collection
public static NameValueCollection GetQueryStringCollection(string url)
{
string keyValue = string.Empty;
NameValueCollection collection = new NameValueCollection();
string[] querystrings = url.Split('&');
if (querystrings != null && querystrings.Count() > 0)
{
for (int i = 0; i < querystrings.Count(); i++)
{
string[] pair = querystrings[i].Split('=');
collection.Add(pair[0].Trim('?'), pair[1]);
}
}
return collection;
}
So, this function is a static one because, we are calling it from a Webmethod. And this function is expecting url as the parameter. Actually, it is not complete url, it is just the complete querystring url which starts from the character '?'. Now, how to call and use this function? Find below.
NameValueCollection collection = GetQueryStringCollection(HttpContext.Current.Request.UrlReferrer.Query);
if (collection != null && collection.Count > 0)
{
string id = HttpContext.Current.Server.UrlDecode (collection["id"]);
}
The above statement returns the querystring value which has the key "id". This way you can get any querystring value, just by passing it's key name to the collection.
HttpContext.Current.Request.UrlReferrer.Query – Which holds the complete querystring url starts from '?'. So, this way you can get the query string data and use it where ever you want in Page Webmethods.
Is this what you are looking for? Or do you have any other ways to get the querystring data? Please post your ideas on it here.
No comments:
Post a Comment