【问题标题】:Razor get null reference when trying to display ItemRazor 在尝试显示项目时获取空引用
【发布时间】:2015-11-07 19:52:56
【问题描述】:

我在 MVC 中有一个基本视图,它将列出我的所有属性。属性模型是这样编码的:

public class Property
{

    public int Id { get; set; }

    [Display(Name = "Type")]
    public PropertyType Type { get; set; }

    [Display(Name = "Address")]
    public Address Address { get; set; }

    [Display(Name = "Area")]
    [Required(ErrorMessage = "A property area is required.")]
    public double Area { get; set; }

}

基本上我有两个外键:类型和地址。我已经能够将一些信息插入到数据库中,如下所示:

所以数据库包含信息,但每次我调用索引视图来列出所有属性时,我都会得到一个 NullReferenceException。

@foreach (var item in Model) {
<tr>
    <td>
        @Html.Display(item.Type.Id.ToString())
    </td>
    <td>
        @Html.Display(item.Address.Id.ToString())
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Area)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
        @Html.ActionLink("Details", "Details", new { id=item.Id }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.Id })
    </td>
</tr>

编辑:空值来自 Controller 类,就像这样:

    public ActionResult Index()
    {
        return View(db.Properties.ToList());
    }

我能做什么?

【问题讨论】:

    标签: c# asp.net-mvc entity-framework razor


    【解决方案1】:

    如果您使用的是 EF,则需要使用以下方式包含您的导航属性:

    db.Properties.Include(i => i.Address).Include(i => i.Type).ToList()
    

    这将进行内部连接,并且应该填充您的属性。

    更多信息请阅读docs

    【讨论】:

      【解决方案2】:
      @Html.DisplayFor(modelItem => item.Area)
      

      我想这是引发错误的那一行。

      取出来看看是否还有错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-16
        • 1970-01-01
        • 1970-01-01
        • 2019-09-22
        • 1970-01-01
        • 2021-09-28
        • 1970-01-01
        相关资源
        最近更新 更多