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

Adding a default value to selected list Razor

我正在填充这样的下拉列表

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

我怎样才能 select 默认值 'Other' 例如

是这样想的

@Html.DropDownListFor(m => m.SelectedPrimary, new SelectList(Model.PrimaryDrop, "Value", "Text", new { SelectedItem = "Other" }), "Select ...", new { @class = "form-control" })

但不起作用

你可以通过服务器代码来实现,当你填充数据时

PrimaryDrop = primaryDrop.Select(item => new SelectListItem
    {
        Value = item.Key,
        Text = item.Value,
        Selected = item.Key == "4" // Or item.Value== "Others"  
    });

或者我们可以为模型的 SelectedPrimary 设置值

SelectedPrimary = "4"

您不需要创建一个对象来指定选中的项目,您只需要给出您想要的。在您的情况下,Other 的值为 4:

@Html.DropDownListFor(m => m.SelectedPrimary, 
                      new SelectList(ViewBag.PrimaryDrop, "Value", "Text", "4"),
                      "Select ...", 
                      new { @class = "form-control" })