I tried to send a collection to view with ViewBag
.
Controller:
var list = db.Groups.Where(g => g.Active).OrderByDescending(g => g.Priority);
ViewBag.Groups = list;
then loop on this collection in View:
View:
@{
var Groups = ViewBag.Groups as IEnumerable<Group>;
}
...
@foreach (var item in Groups)
{...}
But I got exception
Object reference not set to an instance of an object.
I put some breakpoint. This collection has 4 items but foreach
loop trying to loop over 5th item! So I get the null reference exception.
Can someone tell me what exactly happening?
I tried this with List<>
but same problem.