Search code examples
imagerazormodel-view-controllerviewbag

MVC Razor use ViewBag as part of dynamic Image link


I've got an MVC Application and I've got a ViewBag List of Items. I've got the List using Razor to show in a Modal popup and I was hoping to use said list, to dynamically display an image for each item in the list

I'm hoping for something along the lines of "~/Images/ + @ViewBag.List[i] + .jpg"

Does anyone know of a way to achieve this as I've not had much luck so far?

Any assistance on accomplishing this would be greatly appreciated!

Thanks in advance Paul


Solution

  • @foreach(var item in ViewBag.List)
    {
       <img src="~/images/@(item).jpg" />
    }
    

    Should work for you. The issue you were running into is you do not need the:

    + @ViewBag.List[i] +
    

    @ViewBag.List[i] will work inline without any string concatenation.