Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception in MVC - 3 view cannot perform runtime binding on a null reference

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?

like image 698
user1740381 Avatar asked Dec 19 '12 17:12

user1740381


1 Answers

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);
}
like image 82
Bishnu Paudel Avatar answered Oct 21 '22 06:10

Bishnu Paudel