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
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).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:~
It should not appear in javascript. The most direct way is to get rid of~
like below :Or complete the specified path: