MVC - 设置SelectList的选定值

kai*_*lya 54 c# asp.net-mvc

在没有选择值的情况下实例化后,如何设置SelectList的selectedvalue属性;

SelectList selectList = new SelectList(items, "ID", "Name");
Run Code Online (Sandbox Code Playgroud)

我需要在此阶段后设置所选值

wom*_*omp 68

如果您有SelectList对象,只需遍历其中的项目并设置所需项目的"Selected"属性.

foreach (var item in selectList.Items)
{
  if (item.Value == selectedValue)
  {
    item.Selected = true;
    break;
  }
}
Run Code Online (Sandbox Code Playgroud)

或者与Linq:

var selected = list.Where(x => x.Value == "selectedValue").First();
selected.Selected = true;
Run Code Online (Sandbox Code Playgroud)

  • Selected属性是只读的.这个解决方案没有任何意义. (20认同)
  • 这两个选项在MVC3迭代选项中都不起作用:不起作用b/c item.Value不存在.Linq选项:单个项目已成功设置,但列表忽略更新. (4认同)
  • SelectList的SelectedValue属性只是因为没有唯一性保证......据我所知,你真的必须在项目级别处理它. (3认同)
  • 这不是mvc 3中的工作解决方案(也许是其他版本).item.value和item.selected不可用 (3认同)
  • @womp - 你能更新答案以反映最新的约定吗?这是谷歌的顶级结果 (2认同)

Ale*_*ens 22

派对有点晚了,但这里有多简单:

ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82");
Run Code Online (Sandbox Code Playgroud)

这使用我的方法getcountries来填充一个名为countries的模型,显然你将用你的数据源,模型等替换它,然后将id设置为selectlist中的值.然后只需添加最后一个参数,在本例中为"82"以选择默认的选定项目.

[编辑]以下是如何在Razor中使用它:

@Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" })
Run Code Online (Sandbox Code Playgroud)

希望这能节省一些时间.

  • 原帖说"如何在实例化后设置值".这不回答这个问题. (9认同)

mzo*_*erz 13

只需在mvc4中使用第三个参数选择值即可

@Html.DropDownList("CountryList", new SelectList(ViewBag.Countries, "Value", "Text","974"))
Run Code Online (Sandbox Code Playgroud)

这里"974"被选中值指定

在我的结果中选择的国家现在是qatar.in C#如下所示

    foreach (CountryModel item in CountryModel.GetCountryList())
        {
            if (item.CountryPhoneCode.Trim() != "974")
            {
                countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });

            }
            else {


                countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });

            }
        }
Run Code Online (Sandbox Code Playgroud)


Dou*_*mpe 10

为什么要在创建列表后设置值?我猜您是在模型中而不是在视图中创建列表.我建议在模型中创建底层的可枚举,然后使用它来构建实际的SelectList:

<%= Html.DropDownListFor(m => m.SomeValue, new SelectList(Model.ListOfValues, "Value", "Text", Model.SomeValue)) %>
Run Code Online (Sandbox Code Playgroud)

这样,您选择的值始终设置为视图呈现而不是之前.此外,您不必在模型中放置任何不必要的UI类(即SelectList),它可能仍然不知道UI.

  • 当使用强类型的`For`版本的`Html.DropDownList`时,忽略`SelectList`构造函数中的"当前选择的值".尽管获得了6票的错误答案,但做得很好:) (9认同)
  • 你真的有这个工作吗?当我使用这种方法时,它生成下拉精简的html但不是html根据SelectList构造函数的最后一个参数设置所选值. (7认同)
  • 这种方法对我也不起作用. (2认同)

Imm*_*lue 6

除了@Womp答案之外,值得注意的是,可以删除“Where”,并且可以将谓词直接放入“First”调用中,如下所示:

list.First(x => x.Value == "selectedValue").Selected = true;