Tuesday, August 25, 2009

‘Sys’ is undefined - The trivial answer

I struggled a bit with this error this morning.
I read plenty of blog posts about updating the references in your web.config file, mostly related to using pre-3.5 versions of asp.Net. Just google it to find these posts.

This post has a potential solution for .Net 3.5: http://forums.asp.net/t/1355308.aspx

My actual problem, was because I used the call to sys,

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

in the head of my page. To be more exact, I used it in a .js file, which I included in the head. The ScriptResource.axd, which contains the Sys object, doesn't load till after the head (or later on in the head), causing the error.

The solution? Just pop the piece of offending code into the body. The cleaner, nicer way of course, is to register it as a startup script in the serverside code, which I do with the following line:

Page.ClientScript.RegisterStartupScript(this.GetType(), "RegisterEndRequestHandler", "\nSys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);", true);

And with that, my problem is solved!

How did I figure it out?

Some of the posts led me to the fact that the Sys object is defined in ScriptResource.axd. I then had a look at another page which uses AJAX, and noticed that it loads that file along with the other js files.

To see this, your debugger needs to bind to the browser (VS2008 does it automatically), which allows you to debug javascript (very handy!). More info can be found here: http://weblogs.asp.net/scottgu/archive/2007/07/19/vs-2008-javascript-debugging.aspx

I then had a look at the list of loaded scripts when I got the error, and the ScriptResource.axd was missing, along with all the other axd files. Letting flow continue and inspecting it after the page had loaded, revealed that those scripts had now been added to the page. This lead me to try running the code in the body, which worked perfectly.