Page_Load method being called twice (randomly) in ASP.NET web application

First lets look in to the Architecture of this web application which I was working on:

The user will be redirected to a static HTML landing pagefrom where the user selects products using radio buttons and hits an htmlbutton which is coded as follows: 

<input name="image" type="image" src="../Images/buynow.jpg" class="buynowbutton_and"  id="BuyNow_0" onclick="return Redirect(this);"/>

As you can see, when the button is clicked, the javascriptmethod Redirect() is being called.

In this method, a url is constructed using the selected productids and redirected to the shopping cart page.

  document.forms[0].action= url;

 document.forms[0].submit();

 

Now the missing piece is that we should return a “false”after the redirection statement. This will prevent the page from posting  back again(which we don’t want to happen) aswe already redirected the page.

 Otherwise the browsermight get posted back ‘again’(This is quite random and depends on browser. Wehad issues with IE 7 ) and 2 ‘post backs’ will happen on the same page and itwill cause Page_Load to execute twice  ina multithreaded manner sharing the same session variables. This is a dangeroussituation. It leads to unexpected behavior of the ASP.NET application and itaffects the output.

In my case there was an if else loop in the Redirect()method which was causing the issue.

If(condition){

Do something;

//Missed the return false here.

}else

{return false;}

As you saw above the return false was not in if block, itsonly in else block. This code used to work initially and suddenly started tocreate issues.  

 

If your application has a client side redirect,then make sure that you disable the post back  returning a false in the onclick event toprevent the second post back. From another perspective, if you have two ormultiple unexpected Page_Load events happening on your aspx page and you are clueless(just like me initiallyJ), check whether you are returning the false inyour javascript after its execution(make specific checks on conditional statementsin the JS which might prevent the ‘false’ to be returned 

Leave a reply