简体   繁体   English

向选定列表剃刀添加默认值

[英]Adding a default value to selected list Razor

I am populating a dropdown like this 我正在填充这样的下拉列表

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

And displaying it like this 并像这样显示

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

How can I select a default value to 'Other' for example 例如,如何选择默认值为“其他”

Was thinking something like this 在想这样的事情

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

but doesn't work 但不起作用

You can achieve it by server code, when you populate data 填充数据时,可以通过服务器代码实现

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

Or we can set value for SelectedPrimary of model 或者我们可以为模型的SelectedPrimary设置值

SelectedPrimary = "4"

You don't need to create an object to specify the selected item, you just need to give the value you want. 您无需创建对象来指定所选项目,只需提供所需的值即可 In your case, Other has a value of 4 : 在您的情况下, Other的值为4

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM