0
@Html.DropDownListFor(model => model.Members[index].Contact.RelationId.Value, new SelectList(Model.Relations, "RelationId", "Description"), new { @class = "form-control" })

So my list is being created , and model.Members[index].Contact.RelationId.Value = 2 but won't select 2nd id of the DDL only 1st.

enter image description here enter image description here

I've tried this several different ways and stack overflow solutions. not sure what i could be doing wrong

one of the answers attempted

@Html.DropDownListFor(model => model.Members[index].Contact.RelationId.Value, new SelectList(Model.Relations, "RelationId", "Description"),  Model.Members[index].Contact.RelationId.Value)

without effect

Community
  • 1
  • 1
Pakk
  • 1,299
  • 2
  • 18
  • 36
  • When you use `DropDownListFor()` in a loop you must generate a new `SelectList` in each iteration and set the `SelectedValue` property (its an unfortunate limitation of the helper. The alternative is to use a custom `EditorTemplate` for your model and pass the `SelectList` as `additionalViewData` –  Aug 29 '15 at 02:45
  • @StephenMuecke but isn't that what I'm doing ( creating a New select list ) with `, new SelectList(...` per iteration? I'll try the editor template however – Pakk Aug 30 '15 at 19:04
  • 1
    Your creating a new `SelectList` but not setting the setting the SelectedValue property which is necessary when used in a `for` loop –  Aug 30 '15 at 23:29

2 Answers2

1

In this line

@Html.DropDownListFor(model => model.Members[index].Contact.RelationId.Value, new SelectList(Model.Relations, "RelationId", "Description"),  Model.Members[index].Contact.RelationId.Value)

It should be something like:

@Html.DropDownListFor(m => m.Members[4].Contact.RelationId.RelationId, 
new SelectList(Model.Relations, "RelationId", "Description", Model.Members[4].Contact.RelationId.RelationId), new { @class = "form-control" })        

"m => m.Members[4].Contact.RelationId.RelationId" is where value should be saved during post back.

Model.Members[4].Contact.RelationId.RelationId is the selected value in dropdown.

flyfrog
  • 752
  • 1
  • 6
  • 7
0

According to this article on MSDN, there is a constructor on the SelectList class that takes the following arguments:

SelectList Constructor (IEnumerable, String, String, Object)

Where the IEnumerable is the SelectList items, the first String is the key, the second String is the text and and Object is the SelectedValue, which is what I see you are aiming towards.

Therefore, I believe you should try this:

@Html.DropDownListFor(model => model.Members[index].Contact.RelationId.Value, new SelectList(Model.Relations, "RelationId", "Description", model.Members[index].Contact.RelationId.Value), new { @class = "form-control" })

See if it works :)

Mateus
  • 28
  • 6