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.

Dynamic CSS using ASP.NET MVC

I’ve been considering the usefulness of adding a CSS management system to my CMS that I’ve been working on. Here are the steps I’ve taken to implement it.

  1. Create a new MVC applictaion
  2. Open /Views/Shared/Site.Master
    1. <link href=”/Css/Site.css” rel=”stylesheet” type=”text/css” />
    2. This doesn’t point to anything yet
  3. Open Global.asax
    1. Add a MapRoute
      1. routes.MapRoute(“Css”, “Css/{cssFile}.css”, new { controller = “Css”, action = “Index”, cssFile = “Site” });
      2. Now /Css/Site.css points to Css/Index
  4. Add a class Css.cs to Models
    1. Add public string Body { get; set; }
    2. Add public string Width { get; set; }
    3. Add public string Background { get; set; }
  5. Add definitions as desired
  6. Add a view for CssController/Index
    1. Make it strongly typed with CSScontrol.Models.Css as the model
  7. Change contenttype in page directive of Views/Css/Index.aspx to “text/css”
  8. That should do it.

I’m not sure that I’m convinced of the usefulness of this idea but it’s possible and easy to implement in your ASP.NET MVC project. The possibility of using variables in a CSS file is intriguing.

You may download a sample of the MVC2 project here.MVC3 project here. Let me know if this is a good idea, a horrible idea or just a bit interesting.

Edit – I’ve added a Response.Filter to this to remove extra spaces, tabs, carriage returns/new lines, final semicolons and comments. It brought the 4.96kb file down to 2.74kb. It can be enabled/disbled in Web.config using appSettings key CompressCSS (bool)