Asp.net-Mvc

如果在 for 循環中,DropDownListFor 不選擇值

  • April 13, 2010

在我看來

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

在我的控制器中

public int[ ] Countries { get; set; }

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

當表單被發佈時沒有問題,下拉列表被填充並且使用者選擇的值被發布。但是,當我嘗試將已分配值的表單載入到國家 [] 時,它不會被選中。

我也一樣。當使用 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很好地解釋了這一點(感謝 Lance,你的文章真的幫助了我:)

不確定這對 mv4 是新的還是在以前的版本中存在。但是 DropDownListFor 包含一個用於 SelectList 建構子的附加參數。

SelectList(IEnumerable, String, String, Object)

例如:

Html.DropDownListFor( x => x.Countries[ i ], New SelectList(Model.CountryList,"ID","Description",Model.Countries[i]))

ID對像中的國家 IDCountryListDescription國家名稱在哪裡。

引用自:https://stackoverflow.com/questions/2631397