Asp.net-mvc – Iterating through ArrayList in ViewData ASP.NET MVC

asp.net-mvcasp.net-mvc-2

I am writing an application wherein I need to iterate through a ArrayList sent by the controller to the view using Viewdata.

The controller action:

public ActionResult ConfirmItemsList(string[] arr)
{
   // I generate ArrayList here , call it arrayLst

   ViewData["ItemsList"] = arrayLst;
}

Now I need to iterate this ViewData and display as unordered list in the view ( which is not strongly typed ), but am not able to get the syntax of for/foreach right.

I keep getting the error : foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'

Can some one please help me.

Thanks.

Best Answer

I think you are missing a cast. If you know it's an arrayList cast it as such when you pull it out of ViewData. Check out this link for more info.

foreach(item in (ViewData["ItemsList"] as ArrayList))
{
    doSomethingHere();
}
Related Topic