在没有选择值的情况下实例化后,如何设置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)
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)
希望这能节省一些时间.
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.
除了@Womp答案之外,值得注意的是,可以删除“Where”,并且可以将谓词直接放入“First”调用中,如下所示:
list.First(x => x.Value == "selectedValue").Selected = true;
归档时间: |
|
查看次数: |
175308 次 |
最近记录: |