我正在填写像这样的下拉列表
primaryDrop = new Dictionary<string, string>()
{
{"1", "Getting ready"},
{"2", "Starting"},
{"3", "All"},
{"4", "Other"}
};
PrimaryDrop = primaryDrop.Select(item => new SelectListItem
{
Value = item.Key,
Text = item.Value
});
并像这样显示
@Html.DropDownListFor(m => m.SelectedPrimary, new SelectList(Model.PrimaryDrop, "Value", "Text"), "Select ...", new { @class = "form-control" })
如何选择“其他”的默认值,例如
想到这样的事情
@Html.DropDownListFor(m => m.SelectedPrimary, new SelectList(Model.PrimaryDrop, "Value", "Text", new { SelectedItem = "Other" }), "Select ...", new { @class = "form-control" })
但不起作用
答案 0 :(得分:1)
您可以在填充数据时通过服务器代码实现它
PrimaryDrop = primaryDrop.Select(item => new SelectListItem
{
Value = item.Key,
Text = item.Value,
Selected = item.Key == "4" // Or item.Value== "Others"
});
或者我们可以为模型
的SelectedPrimary设置值SelectedPrimary = "4"
答案 1 :(得分:1)
您无需创建对象来指定所选项目,只需要提供所需的值即可。在您的情况下,Other
的值为4
:
@Html.DropDownListFor(m => m.SelectedPrimary,
new SelectList(ViewBag.PrimaryDrop, "Value", "Text", "4"),
"Select ...",
new { @class = "form-control" })