MVC Grid使用id从另一个表获取值

时间:2015-03-18 21:57:13

标签: c# asp.net-mvc telerik

我正在使用Telerik MVC Grid,有两个表:

  public partial class Sleep
    {
        public int ID { get; set; }
        public string PHN { get; set; }
        public System.DateTime Day { get; set; }
        public Nullable<int> SleepLevelId { get; set; }
        public Nullable<int> SDuration { get; set; }
        public string Comment { get; set; }
        public virtual SleepLevel SleepLevel { get; set; }
    }

  public partial class SleepLevel
{
    public SleepLevel()
    {
        this.Sleep = new HashSet<Sleep>();
    }

    public int SleepLevelId { get; set; }
    public string TheLevel { get; set; }

    public virtual ICollection<Sleep> Sleep { get; set; }
}

}

我将第二个模型用于下拉列表。我在这里如何生成网格模型:

private IEnumerable<Sleep> GePB ()
            {
             ....
            var sleep = db.Sleep.Include(s => s.SleepLevel).Where(d => d.PHN == phn && d.Day <= toDate);     
            return sleep;
            }
        [GridAction]
        public ActionResult _AjaxBinding ()
            {
            return View(new GridModel<Sleep>   {  Data = GePB()  });
            }

在Grid中我使用:

 @(Html.Telerik().Grid<Sleep>()
                  .Name("Grid")
                  .DataKeys(keys => keys.Add(p => p.ID))
                  .ToolBar(commands => commands.Insert().ButtonType(GridButtonType.ImageAndText).ImageHtmlAttributes(new
                  {
                      style = "margin-left:0;"
                  }))
                  .DataBinding(dataBinding => dataBinding.Ajax()
                      .Select("_SelectAjaxEditing", "Sleep")
                              .Insert("_InsertAjaxEditing", "Sleep")
                              .Update("_SaveAjaxEditing", "Sleep")
                              .Delete("_DeleteAjaxEditing", "Sleep"))
                  .Columns(columns =>
                  {
                      columns.Bound(p => p.Day).Width(70).Format("{0:d}");
                      columns.Bound(o => o.SleepLevel.TheLevel).Width(70);
        columns.Bound(o => o.SDuration).Width(70);
        columns.Command(commands =>
        {
        commands.Edit().ButtonType(GridButtonType.Image);
        commands.Delete().ButtonType(GridButtonType.Image);
        }).Width(50).Title("Edit");
        })
        .Editable(editing => editing.Mode(GridEditMode.InLine))
        .Pageable()
        .Scrollable()
        .Sortable().Filterable()
        )

我收到以下错误:

Unable to get property 'TheLevel' of undefined or null reference

非常感谢您的建议。

1 个答案:

答案 0 :(得分:0)

Sleep类中没有属性是S tress 级别类型。所以我会尽可能地解决错误信息。

错误

  

无法获取未定义或空引用的属性“TheLevel”

是因为这一行 columns.Bound(o => o.SleepLevel.TheLevel).Width(70);

正在尝试访问SleepLevel类的一个名为TheLevel的属性,该属性很可能在Sleep类中不存在。