Some of you will face this problem when using Bundling and Minification in ASP.NET MVC 4. This post cover about how to fix relative CSS Path in ASP.NET MVC 4.

Recently, I hit a known problem with deploying to IIS virtual directories. It’s not a problem for ASP.NET which understands virtual directories and so if you ask for “~” or “/” will return “yoursite/virtualfolder”. However, JavaScript is run under IIS, which doesn’t understand this idea so well. Do “/” in JS and you’ll get back “yoursite” NOT “yoursite/virtualfolder”.

So what’s the fix? Well, for JavaScript there are a couple of answers. So I check my javascript. Based on this answer, I came up with this:

1. Add a hidden field to a masterpage:

  @Html.Hidden("HiddenCurrentUrl",  Url.Content("~"))

2. As one of the first things you do, ensure this JS runs. All it does it take the value in the field and store it:

var baseUrl = "";
baseUrl = $("#HiddenCurrentUrl").val();


3. Use baseUrl wherever you need to call things in JavaScript:

Silverlight.createObject(
            baseUrl + "ClientBin/SilverlightBridge.xap",  // source
            ...
        );

Hmm… But you know, that is not the problem. The problem is with the CSS file

    .link-button.cancel {
        background-image: url('../Images/appbar.cancel.darkgrey.png');
    }

A similar problem occures where these URLs start with a slash(/) because IIS interprets that incorrectly. You can’t invoke ASP.NET, which does know the right root into a CSS file

After some messing around, I came to this compromise, which works well. It also exposes some of the hidden power of using Bundling:

  1. For any images you reference in CSS, move them into a relative folder, such as /images near the CSS. I know, this may be an unacceptable compromise for you. But actually, it makes a lot of sense. The image is probably only used by the CSS so it makes sense to have it nearby, not in some global /images folder.  
  2. In order to make this work, you need to get your CSS (which you’ve bundled up) into the same place relative to the images you’re reference, or at least, you need to cheat the browser into thinking this happening.
  3. So, for instance:

      bundles.Add(new StyleBundle("~/Content/DataTableStyle").Include(


    comes out the other end as:

Don’t forget that all your “static” content, such as images won’t be affected by Bundling and can be referenced using the folder structure you expect, i.e. the one you’ve set up in Visual Studio.

So… when you create the Style Bundle you give it a name which reflects where you have it in your Visual Studio folder structure, then it will pop out the other end in the same place, relatively, to the image files which it’s references! And because the Bundling is happening via ASP.NET, the URL of the CSS file, and wherever it is referenced, works fine in virtual directories!