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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....