我在我的视图中有一个dropdownList,我想为其分配一个值为0的All选项假设
<option value="0">All</option>
<option value="1">Account A</option>
<option value="2">Account B</option>
依此类推,如果用户默认情况下不选择任何一个选项,其选择的值应该是0全部..我试过的东西不起作用。
这是我的代码,任何帮助将不胜感激。
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");
答案 0 :(得分:5)
您需要在控制器中构建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
)