Friday, March 25, 2011

Tip: JavaScript "unload" event myth for IE8

I came across the needs to save certain state to the web server using Ajax when a user navigates away from a page, so i tried to use the browser (IE8) "unload" event to do it.
One thing that i noticed when using the "unload" event is that, once the user clicks on a new link to navigate to a new page, browser will first send the request to web server causing the "pageLoad" function to be triggered then only the Ajax request is process in the web server.
If the next page that the user navigates to relies on the first page state, there will be problem because the new page is loading without getting the data from previous page.

My workaround is not to rely on the "unload" event, but to use user action to save the state. For example, when the user clicks on a link to do popup, after the popup immediately save the state to server. It's costly but working for now.

Wednesday, March 2, 2011

Tip: Asp.Net Request.InputStream is empty?

Recently I needed to post some json data from browser to web server. I used the following codes to read the input stream:

System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
string json = sr.ReadToEnd();

There's one problem with the above codes, that is the json variable will hold empty string even though I am sure that data is posted to the web server. The resolution of the problem is to always set the stream position to 0. The resulting codes looks like this:

Request.InputStream.Position = 0; System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
string json = sr.ReadToEnd();

Now with the first line of the codes, you will be able to get the stream data.