MVC无法在css中使用background-url显示图像 - 使用捆绑

eye*_*aul 5 css asp.net-mvc

我有一个MVC4项目,它具有以下结构:

/Content/css/sprites/topbar.css

/Content/images/topbar.png

在css文件中我试图通过使用以下方法引用图像:

background: url('../../images/topbar.png')
Run Code Online (Sandbox Code Playgroud)

但图像不显示.如果我更改它,以便图像位于:

/Content/css/sprites/topbar.png

并将css更改为:

background: url('content/css/sprites/topbar.png')
Run Code Online (Sandbox Code Playgroud)

它有效,但这打破了我的项目结构.

有任何想法吗?

编辑

我没有提到别的东西,因为我认为它不相关,但它似乎影响了这一点!

@System.Web.Optimization.Styles.Render("~/MainStyles")用来捆绑和缩小CSS,但如果我采取了这一步,那么它就像我期望的那样工作.如何使用我的项目结构和使用捆绑来完成所有工作?

小智 8

不知道是否有其他人遇到这个问题.但是你可以在你的CSS中使用相对路径.关键是将捆绑包注册到您的实际css所在的同一文件夹的虚拟路径.这样MVC将从该路径中的处理程序请求捆绑的css.

尝试将您的捆绑注册更改为:

bundles.Add(new StyleBundle("~/Content/css/sprites/topbar")
              .Include("~/Content/css/sprites/topbar.css")
            );
Run Code Online (Sandbox Code Playgroud)

然后在你看来 @Script.Render("/Content/css/sprites/topbar")

Mvc将从中请求您编译的css包 /Content/css/sprites/topbar?{some-crazy-token-thing}


eye*_*aul 5

我发现了问题所在。

确实是MVC中使用的捆绑和缩小。当css查找图像时,它是在我的包指向的文件夹中查找当前文件夹,而不是css文件所在的文件夹。