I’m a relative newbie to C#/MVC and I’ve come across an issue when passing a rectangular array to ViewData (and then trying to display the contents from within a View file).
My array is populated from a database query, and as far as I can see it’s coming through fine:
Media [
Images [
[Id (int), Type (int), File (string), Title (string)],
[Id (int), Type (int), File (string), Title (string)],
[Id (int), Type (int), File (string), Title (string)]
]
Videos [
[Id (int), Type (int), File (string), Title (string)],
[Id (int), Type (int), File (string), Title (string)]
]
]
I’m assigning each half of the main array (Images and Videos) to a separate ViewData object in the Controller:
ViewData["Images"] = Media.Images.ToArray();
ViewData["Videos"] = Media.Videos.ToArray();
The View knows that these objects are there, but I can’t seem to figure out how to loop through each array and access each individual index (Id, Type, File, Title) from within the View and add each piece to the View’s HTML code.
One option would be to construct the HTML in the controller, but I really want to avoid that.
Any ideas where I’m going wrong?
EDIT: Here’s the fix, thanks to everyone for prodding me down the right track 🙂
Controller:
ViewBag.Images = Media.Images;
Web.Config:
<namespaces>
<add namespace="Path.to.Models" />
...
</namespaces>
View:
str_code = "<ul>";
foreach (Media image in ViewBag.Images)
{
str_code += "<li>" + image.Title + "</li>";
}
str_code += "</ul>";
Response.Write(str_code);
I assume
Media.Images.ToArray();gives you an array ofMyImageobjects.MyImage
Then the Razor code:
Alternatively you can use the dynamic property
ViewBagavailable in your controller:Then: