2

I'm trying to render a background image in an ASP.NET MVC view using jQuery.backstretch:

$.backstretch("~/Content/img/bug.jpg", { speed: 500 });

However, the GET request in debug returns a 404 because Chrome attaches my application URL route pattern to the file path, like so:

[localhost]/[ControllerName]/~/Content/img/bug.jpg

I've never had this problem before when passing a file path as a parameter in a JS function while using an ASP.NET MVC app. Any suggestions?

2
  • 1
    Maybe you could use relative path somethihg like ../../Cotent/img/bug.jpg Commented Nov 17, 2015 at 4:07
  • Adding the relative path makes the 404 error disappear from the Console, but the image still isn't being referenced as a source or appearing in the view. Commented Nov 17, 2015 at 4:18

2 Answers 2

2

In C#, the relative root path can be referenced by "~/". This tells the web app that the directory of the item you are looking for is relative to the root of the project, rather than the current view.

For example, if you are at the resource /Home/Index, and add the content @Url.Content("img/my_image.png"), then the request will be made to "/Home/Index/img/my_image.png." However, this is likely not where you keep your images, and instead you probably have an image folder in the root of your directory (or, in the MVC world, in the Content folder). So, more likely you desire @Url.Content("~/img/my_image.png").

However, the "~" character does not universally denote the relative root path. If you add "~/" to a link, the browser will interpret the tilde as a directory, and since the link does not contain a root path symbol ("/"), the broswer will create a link relative to the current directory. This results in a path of "/~/...", which, most likely, does not exist.

In short, whenever you are creating relative links in HTML/JavaScript, make sure you omit the "~" character, and this should resolve your issue.

Sign up to request clarification or add additional context in comments.

Comments

1

Use Relative Path using "/"

/RootDirectory/Cotent/img/bug.jpg

If Cotent folder is within the RootDirectory Then Use Below

/Cotent/img/bug.jpg

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.