Unable to use Viewbag List Items in Razor foreach loop

asp.net-mvc, asp.net-mvc-3, asp.net-mvc-4, c#

Solution

Inside the loop in the view, you should use the loop variable:

@foreach (var image in ((List<string>)ViewBag.imageFile)) 
{
    @image
}

`ViewBag.imageFile` is the complete list and will always be, even inside the loop. The `image` loop variable will be the current item from the list on every turn of the loop.

Problem

I have an Images table linked to an Item table (one Item can have many Images). They are linked by the Item Id. I want to return all images for an Item on the details page. I have been trying to use a Viewbag to achieve this (below). Controller: ``` ViewBag.imageFile = (from f in storeDB.Images where f.ItemId == id select f.ImageURL).ToList(); ``` View: ``` @foreach (var image in ((List<string>)ViewBag.imageFile)) { @ViewBag.imageFile } ``` The above will return 'System.Collections.Generic.List`1[System.String]' for each ImageUrl. I believe the issue is that an object is being return rather than the actual List item string value but cannot figure out how to convert it to the string I need. The plan is to edit this foreach to create an img link for each URL. I also have the following Viewbag (testing to see I was able to get the Urls at least): ``` ViewBag.imageURL = string.Join(",", ViewBag.imageFile); ``` The above returns the correct URLs but they are all in one string separated by a comma. Appreciate any help.

Original source