加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 23:45:59 所属栏目:asp.Net 来源:网络整理
导读:在我看来 %= Html.DropDownListFor( x = x.Countries[ i ],Model.CountryList )% 在我的控制器 public int[ ] Countries { get; set; }public ListSelectListItem CountryList { get; set; } 当表单发布时,没有问题,下拉列表被填充,用户选择的值被发布.但是
在我看来
<%= 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(感谢兰斯,你的帖子真的帮助我:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读