2

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?

6
  • And just to clarify, the image path does work by the way. I tried it beforehand with just the image path string in the src="" attribute. Commented Jun 21, 2017 at 14:56
  • Define "does not work". What does it do? What is the client-side HTML generated here? If the client-side code includes the ~ in the path then that certainly won't "work" because that path means nothing to the browser. You'd need to translate it to a client-usable path first, using something like Server.MapPath(). Commented Jun 21, 2017 at 14:57
  • <img id="modalImage" class="thumbnail-lg" src="~/Content/images/1.png"/> works properly (displays my image). However using the @Html.Raw(img) just shows the common error image (blank white image with the broken small square in the top left) Commented Jun 21, 2017 at 15:14
  • I just figure that using a variable to insert the exact same string of text into the <img> tag should work. But it doesn't so I wonder why Commented Jun 21, 2017 at 15:15
  • Is that the actual client-side HTML in the browser? Or the code you're putting in Visual Studio? Look at what's actually in the browser. I suspect that the framework is replacing that path. But isn't replacing it when it's being constructed in the way you're attempting, so you may need to replace it manually. Commented Jun 21, 2017 at 15:17

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

@MattD glad to help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.