使用Serge Zab的助手进行optgroup下拉列表时出错

nie*_*lsv 5 c# asp.net asp.net-mvc optgroup html.dropdownlistfor

我正在尝试使用Serge Zab的optgroup下拉助手,可以在这里找到.

这是我的类别表:
在此输入图像描述

如您所见,我有一个类别,类别也可以是类别中的categoryparent.我希望将parentcategorys作为optgroup,将子项作为optgroup的选项.(只能选择孩子)

在我的ViewModel中:

public short? CategoryId { get; set; }
public IEnumerable<ReUzze.Helpers.GroupedSelectListItem> GroupedTypeOptions { get; set; }
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

[Authorize] // USER NEEDS TO BE AUTHORIZED
public ActionResult Create()
{
    ViewBag.DropDownList = ReUzze.Helpers.EnumHelper.SelectListFor<Condition>();

    var model = new ReUzze.Models.EntityViewModel();
    PutTypeDropDownInto(model);
    return View(model);
}

[NonAction]
private void PutTypeDropDownInto(ReUzze.Models.EntityViewModel model)
{
    model.GroupedTypeOptions = this.UnitOfWork.CategoryRepository.Get()
         .OrderBy(t => t.ParentCategory.Name).ThenBy(t => t.Name)
         .Select(t => new GroupedSelectListItem
         {
             GroupKey = t.ParentId.ToString(),
             GroupName = t.ParentCategory.Name,
             Text = t.Name,
             Value = t.Id.ToString()
         }
     );
}
Run Code Online (Sandbox Code Playgroud)

在我看来:

@Html.DropDownGroupListFor(m => m.CategoryId, Model.GroupedTypeOptions,  "[Select a type]")    
Run Code Online (Sandbox Code Playgroud)

当我尝试运行它时,我总是得到错误:

Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)

我在这个规则上得到了这个错误: .OrderBy(t => t.ParentCategory.Name).ThenBy(t => t.Name)

任何人都可以帮我找到解决这个问题的方法吗?

Joh*_*n H 5

您的错误信息表明,无论是tnullt.ParentCategorynull.

您可以通过简单地检查nulls 来修复错误,但这可能会或可能不会为您提供所需的输出,具体取决于您是否还要包含没有父项的类别.

model.GroupedTypeOptions = this.UnitOfWork.CategoryRepository.Get()
     .Where(t => t.ParentCategory != null)
     .OrderBy(t => t.ParentCategory.Name).ThenBy(t => t.Name)
     .Select(t => new GroupedSelectListItem
     {
         GroupKey = t.ParentId.ToString(),
         GroupName = t.ParentCategory.Name,
         Text = t.Name,
         Value = t.Id.ToString()
     });
Run Code Online (Sandbox Code Playgroud)

我假设你CategoryRepository不能退货null t,但如果可以的话,你会调整到哪里:

.Where(t => t != null && t.ParentCategory != null)
Run Code Online (Sandbox Code Playgroud)