3

I have some markup in my Index.cshtml view, which has an inline css style with the background-image property. When the page is rendered the correct path of the image is not being generated and the tilde remains in the url

HTML Markup:

The path that is used on the img tag works properly when the page is rendered, but the path in the background-image property displays like this and the image is not found

Rendered Markup: enter image description here

<article class="card-item card-item-colored" style="background-image:url(~/build/images/11.jpg);">
                <img class="card-item-pic" src="/build/images/11.jpg" alt="">
                <div class="card-item-hover">
                    <a href="#" class="btn btn-inverse-colored">View Demo</a>
                </div>
                <header class="card-item-caption">
                    <h4>Login Page</h4>
                </header>
            </article>
Jimmy
  • 823
  • 9
  • 12
iambdot
  • 887
  • 2
  • 10
  • 28
  • Can you not remove the tilde? – wazz Aug 05 '17 at 23:11
  • @wazz yes i could remove the tilde, but why doesn't the razor functionality ~/ work as expected? – iambdot Aug 05 '17 at 23:30
  • 1
    Sry, I'm not too familiar with it. Is the styling part of razor syntax? I did some googling and it seems styles can be tricky. One link: https://stackoverflow.com/questions/12351418/mvc-cannot-display-image-using-background-url-in-css-uses-bundling. Second-last answer here: https://stackoverflow.com/questions/9821921/css-background-image-refuses-to-display-in-asp-net-mvc – wazz Aug 05 '17 at 23:43
  • @wazz yes using `@Url.Content()` does work. this styling is not in the css file. it's in the html file. I guess i will just use `@Url.Content()` until i find out why this is happening. thanks – iambdot Aug 06 '17 at 00:13

2 Answers2

13

The use of the tilde (~) in @Url.Content(), and elsewhere in Razor code, will be translated by ASP.NET to reference the root of the current application.

If you use the tilde directly in a string expression, such as within background-image: url() it is not interpreted (parsed) by ASP.NET, and so appears directly as is in the HTML or CSS that is output. This doesn't work because ~ is not a feature of HTML or CSS.

Andy G
  • 19,232
  • 5
  • 47
  • 69
1

Inside a style property, url(...) is a CSS function not a Razor method.

In the CSS url(...) function, start with a forward slash / not a tilda ~ to make a URI relative to the root of your site:

<article style="background-image:url(/build/images/11.jpg);">

The CSS 2.1 specification specifies this in section 4.3.4 URLs and URIs and refers to RFC 3986 for details, which states:

A relative reference that begins with a single slash character is termed an absolute-path reference.

Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467