I have a lot of images I want to display so I'm using a dynamic partial view to reduce unnecessary code. This is my partial view:
@{ string[] imgs = {
"src='~/Content/images/1.png'",
"src='~/Content/images/2.png'",
"src='~/Content/images/3.png'"
};
@foreach (var img in imgs) { *HTML GOES HERE* }
HTML inside foreach loop:
<div class="thumbnail-border">
<img id="modalImage" class="thumbnail-lg" @Html.Raw(img) />
</div>
The strange thing is that if I switch out "src" for "alt", the alt works. But having a variable for src as the image path does not work. So my question is: If I wanted to use a foreach loop to go through an array of strings (the image paths) to use for my , how could I do that?
Forget about @Html.Raw(img) - you don't need it here. Use path only (without src attribute):
@{
var imgs = {
"~/Content/images/1.png",
"~/Content/images/2.png",
"~/Content/images/3.png"
};
}
@foreach (var img in imgs)
{
<img src="@Url.Content(img)" alt="tbd" />
}
Url.Content(img) is used to resolve root path to the image ~/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With