简体   繁体   English

MVC-3视图中的异常无法对空引用执行运行时绑定

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

I am working on MVC-3. 我正在研究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. 我的视图是HomeModel模型类的强类型。 Can anyone please help me to solve this out? 任何人都可以帮我解决这个问题吗?

This is due to the deferred execution of LINQ. 这是由于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. 在您尝试访问它们之前,不会计算Model.Template的结果,在这种情况下,db.Template超出了视图范围。 You can do it by using ToList() to ToArray() and ToDictionary() with db.Templates . 您可以通过使用ToList()ToArray()ToDictionary()db.Templates

Your Controller's code should look like: 您的Controller的代码应如下所示:

public ActionResult Index()
{
    HomeModel model = new HomeModel();

    model.Template = db.Templates.ToList();

    return View(model);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM