MVC5 / C# – Cannot perform runtime binding on a null reference

There are two issues in your code:

Consider this:

public ActionResult Index()
   int n = 0;
   ViewBag.speakers[n] = 5;
   return View();

This simplified piece of code throws Cannot perform runtime binding on a null reference since speakers is not defined (null reference).

You can fix it by defining speakers in the dynamic ViewBag before the loop:

ViewBag.speakers = new List<string>();

The second issue:

ViewBag.speakers[n] = speakers;

speakers in your code is a List, you might want to define ViewBag.speakers as a List<List<string>> and call .Add(speakers) instead of accessing using an index (you might get index was out of range)

Leave a Comment