Home > Enterprise >  Problem with adding images in loop in html executed from javascript
Problem with adding images in loop in html executed from javascript

Time:10-08

I'm trying add images in "for" loop

<div id="p_0" style="text-align:right">
            <picture style="text-align:right;visibility:visible">

                <img src="~/lib/images/Wisielec1.png" alt="Wisielec" style="width:100px;margin-left:inherit">
            </picture>
        </div>
@for(int i = 1; i < 6; i  )
    {
    <div id="p_@i" style="text-align:right">
        <picture style="text-align:right;visibility:visible">
           <img id="pi_@i" src="" alt="Wisielec" style="width:100px;margin-left:inherit">
        </picture>
    </div>
    }

so in JavaScript I have

var images = ['Wisielec1.png', 'Wisielec2.png', 'Wisielec3.png', 'Wisielec4.png', 'Wisielec5.png', 'Wisielec6.png' ];
            document.getElementById("pi_"   j).src = "~/lib/images/"  images[j];

But when I'm loading page there is no images in folder /lib/images visible in Developer tools. Do I have to attach this folder somewhere so that the pictures are uploaded to the server? I can see pictures only when I enter the path of a specific picture in html code. In console I have error : Yes, I'm getting error "Wisielec2.png:1 GET https://localhost:44320/Home/~/lib/images/Wisielec2.png 404

enter image description here

enter image description here

enter image description here

CodePudding user response:

This looks wrong:

"~/lib/images/"

Why are you using a ~ at the start of the path? Notice what it does to the URL:

https://localhost:44320/Home/~/lib/images/Wisielec2.png

This has nothing to do with the code you're writing, you're simply using an incorrect URL. If /Home is in the root of your website then just use that:

"/Home/lib/images/"

Or perhaps use a relative path based on where you're calling it from:

"../lib/images/"

Basically you need to determine what the actual correct URL is for your images and use that.

  • Related