将默认值添加到选定列表Razor

时间:2015-07-10 07:38:21

标签: asp.net-mvc razor drop-down-menu

我正在填写像这样的下拉列表

 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" })

但不起作用

2 个答案:

答案 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" })