Organising JavaScript files in ASP.NET applications.

7 11 2007

Last night I was playing around with the new Virtual Earth V6 map control. I haven’t done a lot of work with Virtual Earth before but I really want to get familiar with it because - well, basically it is cool.

I enlisted Darren’s help to steer me in the right direction if I had any problems and he suggested splitting my JavaScript code out into a separate file, for example in the ~/js/default.aspx.js file for JavaScript associated with Default.aspx.

It was a good idea, but I kinda wanted symmetry with the server-side code behind experience so that I could take this:

image

And turn it into this:

image

The first step is to move the Default.aspx.js file into the same folder as the Default.aspx file, then right mouse click on the web project and select "Unload" (note that this technique only applies to Web Application Projects - but why would you use anything else?).

image

Once the file is unloaded you can directly edit the *.csproj (or *.vbproj) file by right mouse clicking on it in the IDE (a lot of people don’t know about this little trick actually.

image

Once the file is cracked open scroll down to the ItemGroup containing the Default.aspx.js file:

image

You need to modify the text here so that the IDE knows to nest the file under the Default.aspx file. You do this by adding a child DependentUpon element:

image

Once that is done, reload the profile file using the context menu and you should be away!

image 

I think that this technique will lead to a more obvious file structure, and hopefully the ASP.NET team will adopt something similar in future versions of Visual Studio. I have been using Visual Studio 2008 for some time now and love it! Can’t wait until the end of the month.