MVC Razor C# Variable used for HTML img tag src

12,328

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

Share:
12,328
Matt D
Author by

Matt D

Updated on June 05, 2022

Comments

  • Matt D
    Matt D almost 2 years

    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?