ricky89
ricky89

Reputation: 1396

Unable to use Viewbag List Items in Razor foreach loop

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.

Upvotes: 3

Views: 31958

Answers (2)

Chaitra Varkhedi
Chaitra Varkhedi

Reputation: 43

ViewBag does not require a type casting:

@foreach (var image in ViewBag.imageFile)) 
    {
        @image
    }

Upvotes: 1

Anders Abel
Anders Abel

Reputation: 69260

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.

Upvotes: 10

Related Questions