微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc – DropDownListFor在for循环中不选择值

在我看来
<%= Html.DropDownListFor( x => x.Countries[ i ],Model.CountryList )%>

在我的控制器

public int[ ] Countries { get; set; }

public List<SelectListItem> CountryList { get; set; }

当表单发布时,没有问题,下拉列表被填充,用户选择的值被发布.但是当我尝试将已经分配的值的表单加载到Countries []时,它不会被选中.

解决方法

我也是一样的当使用foreach循环一个DropDownListFor(即在页面上呈现多个选择元素)时.

我的工作是将控制器中的所选值设置为视图,如下所示:

在控制器中:

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(感谢兰斯,你的帖子真的帮助我:)

原文地址:https://www.jb51.cc/aspnet/250840.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐