我正在尝试使用serge zab的optgroup下拉式助手,可以找到here
这是我的分类表:
如您所见,我有一个类别,而且类别也可以是类别Parent from a Category。我希望父类作为optgroup,子类作为optgroup的选项。(只能选择子项)
在我的视图模型中:

public short? CategoryId { get; set; }
public IEnumerable<ReUzze.Helpers.GroupedSelectListItem> GroupedTypeOptions { get; set; }

在我的控制器中:
[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()
         }
     );
}

在我看来:
@Html.DropDownGroupListFor(m => m.CategoryId, Model.GroupedTypeOptions,  "[Select a type]")

当我试图运行此程序时,总是会出现错误:
Object reference not set to an instance of an object.

我在这个规则上得到这个错误:.OrderBy(t => t.ParentCategory.Name).ThenBy(t => t.Name)
有谁能帮我找到解决这个问题的办法吗?

最佳答案

您的错误消息表明atnull或at.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()
     });

我假设您的CategoryRepository不能返回nullt,但如果可以,您可以调整位置:
.Where(t => t != null && t.ParentCategory != null)

07-24 17:21
查看更多