views:

192

answers:

1

I'm getting a very peculiar problem with my asp.net application, it took me an age to track down but I still don't know what is causing this behaviour.

If I set a session variable in the Application_PreRequestHandlerExecute event, then my external JavaScript files are ignored, and therfore causing a raft of errors. I have simplified the problem below.

E.g.

I have file called JScript.js containing the code:

function myAlert() {
 alert("Hi World");
}

And in my Default.aspx file I reference the js with the code:

<script src="JScript.js" type="text/javascript"></script>

And in the body onload event I call the myAlert() function:

<body onload="myAlert()">

And finally in the Global.asax file:

Private Sub Application_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)
   HttpContext.Current.Session("myVar") = "MyValue"
End Sub

If you run the Default.aspx file you will see the js function isnt called, however, if you comment out the line of code Global.asax then the external js is called and the function executed when the page loads.

Why is this?

+2  A: 

The PreRequestHandlerExecute event runs twice. Once for the ASPX file and once for the JS file. The problem happens when the PreRequestHandlerExecute event runs when JS file is requested by the ASPX page. Session is NULL (or Nothing) for the JS file which causes an exception. Since an exception occurs for the JS file, the content of this file (your myAlert function) is never loaded into the ASPX page. Therefore, the ASPX page cannot call the myAlert function because the JS file was never loaded.

300 baud
That makes perfect sense. Thanks very much.
Fly_Trap
Is there a way to test which file is causing the PreRequestHandlerExecute to fire? Or would it be better to test if the Session IsNot Nothing before using it.
Fly_Trap