user1740381
user1740381

Reputation: 2199

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?

Upvotes: 7

Views: 6145

Answers (1)

Bishnu Paudel
Bishnu Paudel

Reputation: 2079

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);
}

Upvotes: 8

Related Questions