0

I have a page which creates a variable number of dropdowns and then need to set the value of the selected item but the selected value is not being set. Why is this not working? (the data is definitely correct ie Model.GroupListAll[i] does exist in the selectlist)

@for (int i = 0; i < Model.GroupListAll.Count(); i++)
{               
    @Html.DropDownList("GroupListAll", Model.GroupList.Select(x => new SelectListItem(){Text = x.Text, Value= x.Value, Selected = x.Value== Model.GroupListAll[i] } ), new { @class = "form-control group-list all-list", style = "width:187px" })
}

edit: After reading stephens solution , I have done the following which really is so easy in the end:

  @for (int i = 0; i < Model.GroupListAny.Count(); i++)
            {  
                @Html.DropDownListFor(x => x.GroupListAny[i], Model.GroupList.Select(x => new SelectListItem() { Text = x.Text, Value = x.Value, Selected = x.Value == Model.GroupListAny[i] }))
BMills
  • 881
  • 1
  • 10
  • 24
  • You creating multiple dropdownlists with the same `name` attribute (and also the same `id` attribute which is invalid html) - Your code is a bit pointless since it can never bind correctly to anything. Refer [this answer](http://stackoverflow.com/questions/37407811/mvc5-razor-html-dropdownlistfor-set-selected-when-value-is-in-array/37411482#37411482) for generating dropdownlists in a loop –  Feb 24 '18 at 08:54
  • yeh it never needs to bind to anything as I then save it with an ajax post which grabs the values with a jquery loop. – BMills Feb 25 '18 at 08:18
  • That is crazy (and not an excuse to write bad code!) –  Feb 25 '18 at 08:19
  • I was about to write that I disagree because of what I'm trying to achieve, but I must admit that I think you're right and will try do it with a standard ajax form post. I also amended the edited solution to yours which is much better, thanks! – BMills Feb 25 '18 at 08:36
  • 1
    If you have generated your view correctly (as per the link), then the ajax code also gets far simpler - just `data: $(yourForm).serialize(),` instead of having to use javascript to build the data to post back. And other issues with your code, apart from the invalid html, are that you cannot use mvc's client and server side validation. –  Feb 25 '18 at 08:43
  • Very true Stephen, this post has helped me immensely in adjusting how to approach mvc, thanks again. :-) – BMills Feb 25 '18 at 08:49

0 Answers0