DropDownListFor 在 for 循环中不选择值 [英] DropDownListFor does not select value if in for loop

查看:30
本文介绍了DropDownListFor 在 for 循环中不选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来

<%= 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>

在控制器中的漂亮位是 Selected = o.fruitID == selectedFruit,它的作用类似于 SQL CASE 语句;Lance Fisher (感谢 Lance,你的帖子真的帮了我:)

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 在 for 循环中不选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆