Managing Scripts for Razor Partial Views and Templates in ASP.NET MVC

UPDATE 13-03-2013: I've created a nuget package for the helpers. The original ScriptContext scope had to be brought back in for MVC 4 as the TemplateStack approach no longer worked.
UPDATE 21-11-2011: After some digging through the MVC framework code, I've come up with a slightly cleaner solution that doesn't require ScriptContext to implement IDisposable and therefore removes the need to create a "scope" for the scripts. Skip to the end to see the update.

The view engine in ASP.NET MVC is flexible, very flexible. With great flexibility comes great responsibility however, and managing JavaScript files and code blocks can be particularly cumbersome in conjunction with partial views and templates.