2017-11-11 151 views
0

我有这个元素在我的index.cshtml页:为什么我在客户端出现错误`无法加载资源`?

<section class="parallax parallax-2 padding-xxs" style="background-image: url('mySiteName/assets/images/shutterstoc/img1.jpg');"> 
    <div>some content </div> 
</section> 

正如你可以看到我有样式属性。

如果我改变风格属性,这一点:

style="background-image: url('~/assets/images/shutterstoc/img1.jpg');" 

的背景图像消失,我得到这个错误在Web控制台:

Failed to load resource: the server responded with a status of 404 (Not Found) img1.jpg 

**更新*

The path to the image is: 
http://localhost/assets/images/shutterstoc/img1.jpg 
As you can see the mySiteName is missing. 

更新2: 我试试这个路径:

<section class="parallax parallax-2 padding-xxs" style="background-image: url('./assets/images/img1.jpg')"> 

但我仍然得到上面的错误。 为什么我得到错误Failed to load resource以及如何解决它?

+0

为什么'〜'而不是'.'? –

+0

只是使用'。 '而不是 –

+0

点的意义是什么? – Michael

回答

1

可以在剃刀视图中使用蒂尔达标志~以获取应用根路径。它不适用于CSS样式表文件。

当剃须刀执行该视图时,如果它发现~,它将被转换为应用根目录路径。

只需使用路径没有~

background-image: url('./assets/images/shutterstoc/img1.jpg'); 

图片网址是相对样式表。因此,根据样式表和资产目录的位置,根据需要将前缀.调整为../

.someCssClass { 
    background-image: url('./assets/images/shutterstoc/img1.jpg'); 
} 

就像我如上所述,该图像位置是相对于样式表的位置。如果您在视图/页面中强制编码风格,则它将与页面的网址相关。因此,虽然请求yourSiteBaseUrl/有效,但即使这两条路由返回相同的操作方法和视图/页面,yourSiteBaseUrl/Home/yourSiteBaseUrl/Home/Index也不会起作用,也不起作用。所以我建议不要那样做。

将定义移动到css文件并在其中使用正确的相对路径。它然后将工作yourSiteBaseUrl/Home/IndexyourSiteBaseUrl/HomeyourSiteBaseUrl

+0

感谢发表!之后有什么意义 - '? – Michael

+0

您的意思是? – Shyju

+0

@Michael'.'表示当前文件夹,'..'表示父文件夹 –

相关问题