This article documents a way to read a url parameter from a SharePoint Webpart. This is similar to reading a parameter in an aspx page, but because you are inside SharePoint, there are a couple extras that you need to be aware of.
To better understand this issue, look at the following two urls (not real urls):
These two urls go to the same page, but the latter is passing in information via a url parameter. Specifically, it is saying that a parameter named “Part” is equal to 123 (?Part=123). You can keep appending parameters by using a &. For example, http://www.somesite.com?Part=123&Id=456
But how can I read this information from inside the code of my webpart? Its actually very simple. First, make sure that your webpart class has a reference and is using System.Web – this is not one of the default references.
With that in place, reading a url is a piece of cake! You gain access to the url via an HttpContext. Inside a webpart this is achieved by: HttpContext.Current.Request . We want the query string after the ? in the url. We get a handle to that via QueryString. So using the parameterized url above, we can get the value for the part like so:
Executing this code will yield paramPart to equal “123” which you can then deal with as necessary.
This example works fine as long as you always have a parameter “Part” being passed in. If the url does not have this, then the code will break due to object null reference. So how can we handle that? You could simply surround it with a try catch block. Not very elegant or robust though. A better solution is as follows:
In the above, I declared an enum to cover the different parameters that I want to be able to leverage. The NameValueCollection is a collections of key/value pairs of all the parameters contianed in the url. Then it is a simple matter of looking for the desired parameter. If it is there, do this; else do something else.
This makes for a robust solution that is very easy to understand what is going on inside the code. Of course, make sure you add commenting. What is obvious to you today is not necessarily obvious to others, and it probably won’t be obvious to you the next time you work on this, which will be at least 6 months from now! 🙂
Hope this is helpful.