Dynamic Javascript using ASP.NET MVC

  1. Create a new MVC applictaion
  2. Open /Views/Shared/Site.Master
    1. <script src=”/Scripts/script.js” type=”text/javascript”></script>
    2. This doesn’t point to anything yet
  3. Open Global.asax
    1. Add a MapRoute
      1. routes.MapRoute(“Javascript”, “Scripts/{scriptFile}.js”, new { controller = “Scripts”, action = “Index”, scriptFile = “script” });
      2. Now /Scripts/script.js points to Script/Index
  4. Add a view for CssController/Index
    1. <%= Url.Content(“~/Content/test.jpg”) %>
  5. Change contenttype in page directive of Views/Scripts/Index.aspx to “text/javascript”
  6. That should do it.

Adding strongly typed objects to javascript is now simple to achieve and instead of adding javascript to the <head> in your master page you can just have a dynamically generated and cached .js file.

You may download a sample MVC2 project here.