Exception in MVC-3 view cannot bind runtime to null reference

I am working on MVC-3. In my opinion, I came across the following exception:

cannot perform runtime binding on a null reference 

Model class

  public class HomeModel { public IEnumerable<Html> Template { get; set; } } 

Code view

 @model Project.Models.HomeModel @{ ViewBag.Title = "Home Page"; int i = 0; } <div class="container"> @foreach (var e in Model.Template) //getting exception on this foreach loop { //loop content } </div> 

controller

 public ActionResult Index() { HomeModel model = new HomeModel(); model.Template = db.Templates(); return View(model); } 

My view is strongly typed for the HomeModel model class. Can someone help me solve this problem?

+7
source share
1 answer

This is due to delayed LINQ execution. Model.Template results are not computed until you try to access them, in which case db.Template goes out of scope. You can do this using ToList() to ToArray() and ToDictionary() with db.Templates .

Your controller code should look like this:

 public ActionResult Index() { HomeModel model = new HomeModel(); model.Template = db.Templates.ToList(); return View(model); } 
+8
source

All Articles