0

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.

A.F.N
  • 199
  • 2
  • 15
  • give me team viewer – Sajeetharan Nov 06 '16 at 09:07
  • 1
    Change `ViewBag.AllGroups = list;` to `ViewBag.Groups = list;` ? – Ofiris Nov 06 '16 at 09:30
  • @mybirthname: you and s.akbari are wrong, this question is not about nullvalueexception. Voting to reopen. – jmoreno Nov 06 '16 at 11:37
  • i found problem. i had **another** object (but same class) in ViewBag and that object does not exist (because null assigned to it in controller) . but VS showed me wrong place and tried to loop over 5th item of a list with 4 item!. so i think it is a bug about ViewBag. – A.F.N Nov 06 '16 at 12:20

0 Answers0