ASP.NET MVC Tutorials

How to set image path with StyleBundle:

In this article, you will learn how to resolve absolute path in css file.

We learned in the MVC tutorial that Include method of Bundle class accepts filename with virtual path.

Resolve image path with stylebundle

If you open browser debugger, you can see that css file has been loaded with Status 200.

Resolve image path with stylebundle

However, if site.css contains images with absolute path then images will not load. For example, our following site.css contains footer style as shown below.

site.css:

footer
{
    background:url(../images/border_btm.png) top repeat-x;
    padding:15px;
    color:#618eac;
    margin-top:15px;
}

The above footer style references the background image, which is in the separate images folder.

Resolve image path with stylebundle

However, browser will give 404 error because it could not find image file.

Resolve image path with stylebundle

The browser will consider virtual path for any path given in the css file. It will try to load image from h

Resolve image path with stylebundle

Solution:

If you use absolute path in your css for images then you can specify transformation class CssRewriteUrlTransform.

CssRewriteUrlTransform class rewrites urls to absolute path.

Example: Specify CssRewriteUrlTransform

bundles.Add(new StyleBundle("~/bundles/css").Include(
    "~/Content/css/site.css",
    new CssRewriteUrlTransform()
    ));

Now, image path in the css file will be transform to absolute path.

Resolve image path with stylebundle

As you can see in the above figure, image is loaded using absolute path from root folder.

;