0

I have the following folder structure:

Pages/
  |- Account/
       |- Login/
            |- index.cshtml
  |- Shared/
       |- _Layout.cshtml
|- wwwroot/
    |- 0.png
    |- 1.png

_Layout.cshtml:

<img id="landing_page_image" src="~/0.png" alt="Login" style="height: 100%; width:100%"/>
<script type="text/javascript">
    setInterval(function() {
        let img = document.getElementById('landing_page_image');
        img.src = `~/${Math.round(Math.random())}.png`;
    }, 6000);
</script>    

I get the following error as seen in the browser console:

Account/Login/~/1.png 404

The path is wrong. How to access wwwroot/image.png from the javascript in _Layout.cshtml?

Kok How Teh
  • 3,298
  • 6
  • 47
  • 85

3 Answers3

1

The ~ is Razor syntax. When writing Javascript, you need to use the actual path (which is /1.png, with the slash defining it as an absolute path).

Jeanot Zubler
  • 979
  • 2
  • 18
1

The ~ operator only works in markup and server side code and not in javascript. Thats why your image url does not get resolved correctly. To access your image in your wwwroot directory simply create the path without the ~ operator:

img.src = `/${Math.round(Math.random())}.png`;
Jonas Weinhardt
  • 913
  • 4
  • 11
0

~ It should not appear in javascript. The most direct way is to get rid of ~ like below :

img.src = `/${Math.round(Math.random())}.png`
Jiayao
  • 510
  • 3
  • 7