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 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 thei
variable you are using in your lambda expression coming from and thisx.CountryList
used in the helper won't compile asx
is not defined.Model:
View:
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 afor
loop.You might try this instead:
Model:
View:
Instead of using a IEnumerable in your viewmodel use a List of objects like this one:
And in your view when you assign the selectable elements for the dropdownlist in the loop, do it this way:
Where "Key" and "Description" are PairVM's properties
I know this question is a bit old but I just came across this problem with looping through a list of objects and attempting to bind the values to DropDownListFor(s) in my Edit View.
I overcame the issue with an inline solution by using the logic from some of the previous solutions given by others for this question.
Binding to my Model:
Model.QuestionActionTypes is a SelectList that is populated in my Controller.
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:
In the view
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 :)This is a bit of a hack, and JavaScript reliant but it worked very well for me.
You'll need to know the client IDs that will be produced by the fields (usually these can be worked out manually but for safety you may want to use something like a FieldIDFor method.
You just need to set the values based on the model, in jQuery's $(document).ready:
Not sure if this is new to mv4 or if it exists in prior version. But the DropDownListFor includes an additional parameter for the SelectList Constructor.
For example:
Where
ID
is the Country ID in theCountryList
object andDescription
is the Country Name.