我的 View 中有一个 dropdownList,我想为其分配值为 0 的 All 选项假设
<option value="0">All</option>
<option value="1">Account A</option>
<option value="2">Account B</option>
依此类推,如果用户默认情况下不选择任何一个选项,则其选择的值应为 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" })
Controller
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>
在 Controller 中添加 SelectListItem
与您想要的文本和值。将您的属性更改为
public IEnumerable<SelectListItem> Account { get; set; }
在 Controller 中
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;
然后在 View 中
@Html.DropDownListFor(m => m.SelectedAccount, Model.Account, new { @class = "form-control" })
(Team
同上)
关于asp.net-mvc - 将 dropdownListfor 分配给 value=0 的 "All"选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30640740/