ASP.Net Core 7 Razor javascript how to access `wwwroot/image.png`?

127 Views Asked by At

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?

3

There are 3 best solutions below

0
Jeanot Zubler On

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).

0
Jonas Weinhardt On

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`;
2
Jiayao On

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

img.src = `/${Math.round(Math.random())}.png`