Search code examples
asp.net-mvcasp.net-mvc-2drop-down-menuhtml-helper

DropDownListFor does not select value if in for loop


In my view

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

in my controller

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.


Solution

  • 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:

    In the controller:

    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; }        
    }
    

    In the view

    <table>                        
       <% for (int i=0; i < Model.collectionOfFruitLists.Count; i++ )
            { %>
            <tr>                            
                <td><%: Html.DropDownList("fruitSelectList", collectionOfFruitLists[i].fruits, "Please select...") %></td>                
            </tr>
            <%} %>
     </table>
    

    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 :)