I am working on MVC-3. I am facing the following exception on my view :
cannot perform runtime binding on a null reference
Model class
public class HomeModel
{
public IEnumerable<Html> Template { get; set; }
}
View Code
@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 to HomeModel model class. Can anyone please help me to solve this out?
This is due to the deferred execution of LINQ. The results of Model.Template are not calculated until you try to access them and in this case db.Template is out of scope from view.
You can do it by using ToList()
to ToArray()
and ToDictionary()
with db.Templates
.
Your Controller's code should look like:
public ActionResult Index()
{
HomeModel model = new HomeModel();
model.Template = db.Templates.ToList();
return View(model);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With