October 2010 - Posts

Web page crashes when passing data through Query String

If you are a web developer like me, then I am sure you have used QueryString collection at some stage. Although ASP.Net offers some nifty ways to transfer data, but regardless, there are still many situations in which you need to pass data from one web page to another.

In one of my recent projects, I had the need to build a generic template. This template contained a data grid view control that was responsible for building and populating the grid dynamically from twenty different objects. Each object had an unknown number of columns. So every time I had to pass values from one page to another, I couldn’t think of anything better but to use a query string.

 

While Query string has its benefits, it also has shortcomings.

If you want to pass single or multiple parameters so long as you pass name value pairs, query string really shines. However, when you start to pass 500 or so bytes of data assigned to a parameter, things can get rather nasty. It will most likely throw an exception I hope you get the picture.

lnk.NavigateUrl = "~/MyProject/" & TargetForm & "?Id=" + sMyId + _

                                    "&Code=" + sCode + "&Description=" + Server.HtmlEncode(sDesc) + _

                                    "&SeqNum=" + sSeqNum + "&ActiveInd=" + sActiveInd + _

                                    "&ParentId=" + ParentId + "&Name=" + sName

 

While the above will work so long as you don’t fill the description with over 500 bytes of data.

As a good measure, you can do a check before passing the data as such:

if (sDesc.Length > 550) {

            sDesc = string.Empty;

}

Now in the target page, check to see description’s length is 0. If so, get the data directly from the database to avoid a potential crash like so:

if (Request.QueryString("Description") != null) {

            sDesc = Server.HtmlEncode(Request.QueryString("Description").ToString);

            if (sDesc.Length == 0) {

                        sDesc = getDescriptionByID(sId);

            }

}

 

Obi />