Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Razor C# Variable used for HTML img tag src

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?

like image 917
Matt D Avatar asked Dec 31 '25 10:12

Matt D


1 Answers

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 ~/.

like image 149
Andrei Avatar answered Jan 03 '26 02:01

Andrei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!