c# - 使用 Serge Zab 的帮助程序进行 optgroup 下拉菜单时出错

标签 c# asp.net asp.net-mvc html.dropdownlistfor optgroup

我正在尝试使用来自 Serge Zab 的 optgroup 下拉帮助器,可以找到 here .

这是我的类别表:
enter image description 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)

谁能帮我找到这个问题的解决方案?

最佳答案

您的错误消息表明 tnullt.ParentCategorynull

您可以通过简单地检查 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/

相关文章:

javascript - 关闭和打开 jquery popUps 添加多个按钮

c# - WCF 使用自定义 ApplicationPool Identity 慢 3 倍

asp.net - 如何向 ASP.NET 中的文件发送电子邮件?

asp.net - 加密 Web.config 并安装

asp.net - 获取 ASP.NET MVC 站点在文件系统中的路径

asp.net-mvc - EF Core 3.1 是否支持 DB First 方法?

c# - Office 365 Exchange Online - 客户端凭据 - IMAP 无身份验证

c# - 尝试访问Docker容器时对等连接重置

c# - 如何返回 MemoryStream docx 文件 MVC?

c# - 如何使用 Microsoft Visual Studio 2012 运行负载测试?