How to display a list using ViewBag
simply using Viewbag data as IEnumerable<> list
@{
var getlist= ViewBag.Listdata as IEnumerable<myproject.models.listmodel>;
foreach (var item in getlist){ //using foreach
<span>item .name</span>
}
}
//---------or just write name inside the getlist
<span>getlist[0].name</span>
In your view, you have to cast it back to the original type. Without the cast, it's just an object.
<td>@((ViewBag.data as ICollection<Person>).First().FirstName)</td>
ViewBag is a C# 4 dynamic type. Entities returned from it are also dynamic unless cast. However, extension methods like .First() and all the other Linq ones do not work with dynamics.
Edit - to address the comment:
If you want to display the whole list, it's as simple as this:
<ul>
@foreach (var person in ViewBag.data)
{
<li>@person.FirstName</li>
}
</ul>
Extension methods like .First() won't work, but this will.
To put it all together, this is what it should look like:
In the controller:
List<Fund> fundList = db.Funds.ToList();
ViewBag.Funds = fundList;
Then in the view:
@foreach (var item in ViewBag.Funds)
{
<span> @item.FundName </span>
}