I'm trying to work with the optgroup dropdown helper from Serge Zab that can be found here.
This is my category table:
As you can see I have a category and a category can also be categoryparent from a category. I want to have the parentcategorys as optgroup and the children as options of the optgroup. (Only the children can be selected)
In my ViewModel:
public short? CategoryId { get; set; }
public IEnumerable<ReUzze.Helpers.GroupedSelectListItem> GroupedTypeOptions { get; set; }
In my 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()
}
);
}
In my View:
@Html.DropDownGroupListFor(m => m.CategoryId, Model.GroupedTypeOptions, "[Select a type]")
When I try to run this I always get the error:
Object reference not set to an instance of an object.
I get this error on this rule : .OrderBy(t => t.ParentCategory.Name).ThenBy(t => t.Name)
Can anybody help me find a solution for this problem?
Your error message suggests that either a
t
isnull
or at.ParentCategory
isnull
.You can fix the error by simply checking for
null
s, but this may or may not give you the desired output, depending on whether you also want to include categories that don't have a parent.I'm assuming your
CategoryRepository
can't return anull
t
, but if it can, you'd adapt the where to be: