1

I have a model, which has a List<SelectListItem> which holds a list of Third Parties.

In my view, I need to iterate through the list, and create a DropDownList for that data, based on an id I have, called 'SelectedEntityId'.

I do the formal ForEach:

@foreach (var line in Model.Lines) {

And then, I attempt to render my drop down list:

@Html.DropDownListFor(x=>line.SelectedEntityId, new SelectList(Model.ThirdParties, "Value", "Text"), "Select One", new{@class="form-control"})

However, even though I see (in debug mode) that the 'SelectedEntityId' has the value of 5 (in this case), and that Model.ThirdParties has that item value - the drop down doesn't display that item, but rather its at 'Select One'.

I think it's possible my syntax x=>line.SelectedEntityId is incorrect?

I am getting a warning on the word "line" therem saying "Access to foreach variable in closure. May have different behaviour when compiled with different versions of compiler."

Can I do that, in a foreach, and reference the value of the item in my foreach like that?

tereško
  • 58,060
  • 25
  • 98
  • 150
Craig
  • 18,074
  • 38
  • 147
  • 248
  • 2
    Maybe not related, but if `ThirdParties` is already `IEnumerable` why are you creating a new `SelectList` from it? Note also this wont post back correctly as all the dropdowns will have the same `name` attribute - for that you need a `for` loop so the controls are correctly indexed –  Oct 12 '14 at 09:05
  • Just use `for` loop instead of `foreach` loop. – Lanorkin Oct 12 '14 at 09:57
  • Thanks! How should I do the 'For' version there? The answer to that will provide me with the way forward. – Craig Oct 12 '14 at 21:05
  • 1
    `for(int i = 0; Model.Lines.Count; i++) { @Html.DropDownListFor(m => m.Lines[i].SelectedEntityId, Model.ThirdParties, "Select One", new { @class="form-control" });` –  Oct 12 '14 at 22:14

1 Answers1

0

what is line here. As i am familiar it should be like x=>x.SelectedEntityId however rest code is fine and it should work well guessing you have Value and Text fields in your List. i've seen some examples too related to this have a look on below links if you still facing some issue.

html-dropdownlistfor

stack overflow question

Community
  • 1
  • 1
Deeps
  • 330
  • 1
  • 5
  • 16