1

I have retrived a data list from database. The datalist works fine in controller class and does indeed have values in it but when I bind it with ViewBag.List and try to render it in view it give NullReferenceException. I have no idea why would it gives that exception.
ControllerClass

public ActionResult Index()
{ 
    var SomeList = Database.somelamdaexp.ToList();
    ViewBag.List = SomeList;
    return View();
}

View

@foreach(var item in ViewBag.List)
{
    <tr>
        <td>@item.Field1<td>
        <td>@item.Field2</td>
    </tr>
}
Hooman Bahreini
  • 11,018
  • 7
  • 41
  • 74

1 Answers1

1

Your the usage of ViewBag is correct, I cannot reproduce the problem, see this fiddle

The problem could be because Field1 or Field2 does not exist in your model, or the exception is thrown somewhere else in your code.

Hooman Bahreini
  • 11,018
  • 7
  • 41
  • 74