asp.net 如何对下拉列表进行分组C#

1sbrub3j  于 2023-05-19  发布在  .NET
关注(0)|答案(1)|浏览(122)

在我的asp.net MVC Web应用程序中,我创建了一个模型,如下所示:

[Key]
public int ID {
  get;
  set;
}

[Required]
public string AccountName {
  get;
  set;
}

public string Description {
  get;
  set;
}

public int ? CurrentAccountID {
  get;
  set;
}

所以从控制器,我把数据绑定到ViewBag,就像,

ViewBag.CurrentAccountID = new SelectList(db.Accounts.Where(x => x.Status == true && x.CompanyID == CompanyID), "ID", "AccountName");

这是现在存储在数据表中的数据示例。

但在视图中,我想在下拉列表中显示列表,

收入

银行
信用卡

费用

办公费用
其他费用
因此,方法是我想分组并在下拉列表中显示MainAccountID明智的数据。
如果有人指导我怎么做,我将不胜感激
这是html视图

<div class="col-sm-8"> 
    @Html.DropDownList("CurrentAccountID", null, "--Select Account Type--", htmlAttributes: new { @class = "form-select acctype", @Id = "AccountTypes", @required = true, oninvalid = "this.setCustomValidity('Please Select the Account Type')", oninput = "this.setCustomValidity('')", })
46scxncf

46scxncf1#

第一步是在父帐户中包含导航属性:

public virtual Account ParentAccount { get; set; }

然后包括父帐户,并按父AccountName分组:

var accountsGrouped = db.Accounts
    .Include(x => x.ParentAccount) // Include parent accounts
    .Where(x => x.Status == true && x.CompanyID == CompanyID)
    .OrderBy(x => x.ParentAccount.AccountName)
    .GroupBy(x => x.ParentAccount.AccountName) // Group by parent account name
    .ToList();

ViewBag.AccountsGrouped = accountsGrouped;

然后,您必须手动创建select元素以及optionoptgroup元素:

<div class="col-sm-8">
    <select id="AccountTypes" name="CurrentAccountID" class="form-select acctype" required oninvalid="this.setCustomValidity('Please Select the Account Type')" oninput="this.setCustomValidity('')">
        <option value="">--Select Account Type--</option>
        @foreach (var group in ViewBag.AccountsGrouped)
        {
            <optgroup label="@group.Key"> <!-- group.Key is the parent AccountName -->
                @foreach (var item in group)
                {
                    <option value="@item.ID">@item.AccountName</option>
                }
            </optgroup>
        }
    </select>
</div>

相关问题