将 dropdownListfor 分配给值为 0 的 "All" 选项

assign a dropdownListfor to an "All" option with value=0

在我看来,我有一个下拉列表,我想为其分配值为 0 的所有选项假设

<option value="0">All</option>
<option value="1">Account A</option>
<option value="2">Account B</option>

等等,如果用户没有 select 任何一个选项,默认情况下它的 selected 值应该是 0 All.. 我试过的是行不通的。

这是我的代码,如有任何帮助,我们将不胜感激。

public class ReportViewModel
    {
        public SelectList Account { get; set; }
        public string SelectedAccount { get; set; }

        public SelectList User { get; set; }
        public string SelectedUser { get; set; }
public SelectList Team { get; set; }
        public string SelectedTeam { get; set; }
}

查看

@Html.DropDownListFor(m => m.SelectedAccount, (IEnumerable<SelectListItem>)Model.Account, " ALL ", new { @class = "form-control" })

 @Html.DropDownListFor(m => m.SelectedTeam, (IEnumerable<SelectListItem>)Model.Team, " ALL ", new { @class = "form-control" })

控制器

reportViewModel.Account = new SelectList(preFlightDbContext.Accounts.Where(o => o.AccountId != 0 && o.Deleted == false), "AccountId", "AccountName");
reportViewModel.Team = new SelectList(preFlightDbContext.Teams.Where(o => o.TeamId != 0 && o.Deleted == false), "TeamId", "TeamName");

您需要在控制器中构造List<SelectListItem>,并添加一个SelectListItem,其中包含您想要的文本和值。将您的 属性 更改为

public IEnumerable<SelectListItem> Account { get; set; }

并在控制器中

List<SelectListItem> accounts = preFlightDbContext.Accounts
    .Where(o => o.AccountId != 0 && o.Deleted == false)
    .Select(o => new SelectListItem()
    {
      Value = AccountId.ToString(), // assumes AccountId is not a string
      Text = AccountName
    }).ToList();
accounts.Insert(0, new SelectListItem() { Value = "0", Text = "All" });
reportViewModel.Account = accounts;

然后在视图中

@Html.DropDownListFor(m => m.SelectedAccount, Model.Account, new { @class = "form-control" })

Team 同上)