skip to Main Content

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

Answers


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

    Login or Signup to reply.
  2. 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`;
    
    Login or Signup to reply.
  3. ~ It should not appear in javascript. The most direct way is to get rid of ~ like below :

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

    Or complete the specified path:

    img.src = `/wwwroot/${Math.round(Math.random())}.png`
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search