问题描述
在我看来
<%= Html.DropDownListFor( x => x.Countries[ i ], Model.CountryList )%>
在我的控制器
public int[ ] Countries { get; set; }
public List<SelectListItem> CountryList { get; set; }
在形式被公布是没有问题的,下拉填充的值和用户选择的发布。但是,当我尝试用已赋值加载形式向国家[]它不会选择的。
When the forms gets posted there is no problem, the dropdown is populated and the values the user selects are posted. But when I try to load the form with already assigned values to the Countries[ ] it does not get selected.
推荐答案
我得到相同的了。当使用的foreach循环围绕DropDownListFor(即呈现一个页面上的多个选择元素)。
I'm getting the same too. When using foreach to loop around a DropDownListFor (i.e. to render multiple select elements on a page).
我的解决办法是在控制器而不是视图,设置所选值:是这样的:
My work around is to set the selected value in the controller rather than the view: something like this:
在控制器:
public class FruitList
{
public int? selectedFruit{ get; set; }
public List<SelectListItem> fruits
{
get
{
fruitEntities F = new fruitEntities();
List<SelectListItem> list = (from o in F.Options
select new SelectListItem
{
Value = o.fruitID,
Text = o.fruit,
Selected = o.fruitID == selectedFruit
}).ToList();
return list;
}
}
}
public class ViewModel
{
public List<FruitList> collectionOfFruitLists { get; set; }
}
在视图
<table>
<% for (int i=0; i < Model.collectionOfFruitLists.Count; i++ )
{ %>
<tr>
<td><%: Html.DropDownList("fruitSelectList", collectionOfFruitLists[i].fruits, "Please select...") %></td>
</tr>
<%} %>
</table>
的漂亮位选择= o.fruitID == selectedFruit
中,就像一个SQL CASE语句的控制器;这实在是深受兰斯费舍尔一个解释>(感谢兰斯,你真的后帮我了:)
The nifty bit is Selected = o.fruitID == selectedFruit
in the controller which acts like a SQL CASE statement; this is really well explained by Lance Fisher (thanks Lance, your post really helped me out :)
这篇关于如果在循环DropDownListFor没有选择价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!