About My Blog



Whenever I get stuck doing something - the time comes to venture in the world of internet to find solution. In most cases I do find the solution, solve my problem and go on with my life. Then one day I am faced with the same problem. But now - I can't remember how the hell I solved it the first time. So the cycle begins again. Then I thought, what if I can remember all the those things? So here it is, my Auxiliary Memory. I decided to save all the problems and their solution in this blog so that I can get back to them when I need them. And the plus point is - so can everybody else.

Saturday, March 28, 2015

Handling QueryStrings in ASP.Net

The simplest way to access query string values in ASP.Net would be -
Request.QueryString["param_name"]
//or simpler
Request["param_name"]

But if we keep accessing it this way throughout our code, soon the whole think would become very messy. What if we needed to change the name of the parameter at a later point. Then we have to dig through the code to replace all the instances where we accessed the parameter.

Another way would be to read and store the value of the parameter to a variable in page load and use the variable everywhere. But this would mean that the query string is parsed in every page load even if the value is not used for some particular post backs.

So, a better way would be to encapsulate the access to a function or property -
private string ParamName
{
   get
   {
       return Request.QueryString["param_name"];
   }
}

This is much better, now we can just call the property when we need it and keep our page load method clean. This does query the QueryString every time we call the property which we can easily avoid by storing the value in a variable during first call of the property-
private string _paramName;
private string ParamName
{
   get
   {
       if(_paramName != null)
           return _paramName;
       else
       {
           _paramName = Request.QueryString["param_name"];
           return _paramName;
       }
   }
} 


But what if the parameter was not passed during page call? Then the code will throw a Null exception. The QueryString's Get method takes care of the. The method returns empty string if the parameter is not passed. So the best way to handle QueryString would be -
private string _paramName;
private string ParamName
{
   get
   {
       if(_paramName != null)
           return _paramName;
       else
       {
           _paramName = Request.QueryString.Get("param_name");
           return _paramName;
       }
   }
} 


Now we can easily use the property in our code without facing any runtime error-
if(!string.IsNullOrEmpty(ParamName))  // use ParamName