Dynamically generating client-side script in an ASP.NET page

UPDATE: I have left this article here for historical reasons but you should now consider ASP.NET Web Forms as obsolete due to it not supporting unit-testing and the amount of data that is passed between client and server. I recommend a modern web technology such as MVC 4 (or later) combined with javascript libraries such as jQuery and Knockout.

This is a neat little trick to generate dynamic JavaScript on the server, prior to calling it on the client. At first glance it seems like (a) voodoo, and (b) rather pointless. But the more AJAX web pages you write, the more you find yourself needing clever tricks like this to solve the great client/server divide which you will come up against time and time again. Although this is a very simple example, the potential of being able to create your own javascript at runtime is enormous and I just know that one day this will come in very useful.

Web form markup (client):

Code behind (server):

The rather obvious point to stress here is that you must define and register your dynamic script when the page loads otherwise client-side controls won’t be able to call it. So the server-side Page_Load event handler is the ideal place to do this.


About Phil Munro

I have been developing commercial desktop and distributed web applications with Microsoft technologies since 1997.
This entry was posted in ASP.NET Web Forms, C#, Javascript. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s