我正在尝试使用来自 Serge Zab 的 optgroup 下拉帮助器,可以找到 here .
这是我的类别表:
如您所见,我有一个类别,类别也可以是类别的类别父级。我希望将父类别作为 optgroup,将子类别作为 optgroup 的选项。 (只能选择 child )
在我的 ViewModel 中:
public short? CategoryId { get; set; }
public IEnumerable<ReUzze.Helpers.GroupedSelectListItem> GroupedTypeOptions { get; set; }
在我的 Controller 中:
[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)
谁能帮我找到这个问题的解决方案?
最佳答案
您的错误消息表明 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 到是:
.Where(t => t != null && t.ParentCategory != null)
关于c# - 使用 Serge Zab 的帮助程序进行 optgroup 下拉菜单时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20849531/