Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC cannot display image using background-url in css - uses bundling

I have an MVC4 project which has the following structure:

/Content/css/sprites/topbar.css

/Content/images/topbar.png

In the css file I am trying to reference the image by using:

background: url('../../images/topbar.png')

But the image is not displayed. If I change it so that the image is located in:

/Content/css/sprites/topbar.png

And change the css to be:

background: url('content/css/sprites/topbar.png')

it works, but this breaks my project structure.

Any ideas?

EDIT

I didn't mention something else as I didn't think it was relevant, however it appears to affect this!

I use @System.Web.Optimization.Styles.Render("~/MainStyles") to bundle and minify the css, but if I take that step out, then it works as I would expect. How would I get it all to work with my project structure and using the bundling?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Don't know if anyone else was having this problem. But you CAN use relative paths in your css. The key is registering the bundle with a virtual path to the same folder where your actuall css will reside. This way MVC Will request the bundled css from a handler in that path.

Try changing your bundle registration to:

bundles.Add(new StyleBundle("~/Content/css/sprites/topbar")
              .Include("~/Content/css/sprites/topbar.css")
            );

Then in your view @Script.Render("/Content/css/sprites/topbar")

Mvc will request your complied css bundle from /Content/css/sprites/topbar?{some-crazy-token-thing}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...