views:

369

answers:

2

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.

A: 

A select box sends a single value, so the Countries property should not be an array. Also in your post it is not clear where's the i variable you are using in your lambda expression coming from and this x.CountryList used in the helper won't compile as x is not defined.

Model:

public class MyModel
{
    public int SelectedCountry { get; set; }
    public List<SelectListItem> CountryList { get; set; }
}

View:

<%= Html.DropDownListFor(x => x.SelectedCountry, Model.CountryList) %>

UPDATE:

According to the comment it seems that there are multiple drop downs. I suspect that the problem might come from the i variable used as index in a for loop.

You might try this instead:

Model:

public class MyModel
{
    public int[] Countries { get; set; }
    public List<SelectListItem> CountryList { get; set; }
}

View:

<% foreach (var country in Model.Countries) { %>
    <%= Html.DropDownListFor(x => country, Model.CountryList) %>
<% } %>
Darin Dimitrov
The x.CountryList was just a typo in the question above. The "i" comes from a simple for loop. I have multiple dropdownlists, and x.Countries[i] holds the value of the selected item.
Iceman
Please see my update.
Darin Dimitrov
The "i" is not the problem I think, because when I post the form the values from the dropdowns are posted correctly into the Countries[] property.
Iceman
A: 

i have the same problem

http://stackoverflow.com/questions/3501498/dropdownlistfor-not-binding-on-edit-view-with-repeating-items-listt

the for or foreach does not change a thing... is this an MVC bug?

Stefanvds