我正在尝试使用Serge Zab的optgroup下拉助手,可以找到here。
这是我的类别表:
正如您所看到的,我有一个类别,类别也可以是类别中的categoryparent。我希望将parentcategorys作为optgroup,将子项作为optgroup的选项。 (只能选择孩子)
在我的ViewModel中:
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)
有人可以帮我找到解决这个问题的方法吗?
答案 0 :(得分:5)
您的错误消息表明t
为null
或t.ParentCategory
为null
。
您可以通过简单地检查null
来修复错误,但这可能会或可能不会提供所需的输出,具体取决于您是否还要包含没有父级的类别。
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
无法返回null
t
,但如果可以的话,您可以调整其中的位置:
.Where(t => t != null && t.ParentCategory != null)
答案 1 :(得分:1)
问题是并非所有返回的实体都有一个ParentCategory。
看来你应该只选择孩子而不是父母。
试试这个:
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()
}
);