0

I have seen this question, but still unclear about the following:

I have a SelectListItem that I populate like this:

MySelectList.Insert(0, new SelectListItem { Text = "Text0", Value = "0" });
MySelectList.Insert(1, new SelectListItem { Text = "Text1", Value = "1" });

And in my view I display it like this:

@Html.DropDownListFor(m => m.MyId, Model.MySelectList, new { @class = "form-control" })

If I select Text0 and post the model to controller, MyId contains the the selected value, which is perfect.

But when I go through MySelectList, the Selected value is not set to true for any of the items in the list:

enter image description here

I know I can use MyId to find the selected value, but is there any way to get Selected set to true when user selects an item from the Drop Down and post the form?

Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137
  • Possible duplicate of [How to get DropDownList SelectedValue in Controller in MVC](https://stackoverflow.com/questions/27901175/how-to-get-dropdownlist-selectedvalue-in-controller-in-mvc) – Just code Jul 23 '18 at 09:26
  • @Justcode: thanks for this. Are you referring to the answer by Ehsan Sajjad? I might be missing something here, but that answer is explaining how to post the selected text, not setting selected flag. – Hooman Bahreini Jul 23 '18 at 09:35
  • 1
    [This answer](https://stackoverflow.com/questions/41719293/mvc5-how-to-set-selectedvalue-in-dropdownlistfor-html-helper/41731685#41731685) explains how it works internally –  Jul 23 '18 at 10:09

1 Answers1

1

This is not meant to be ever updated automatically by the Framework. When you examine the HTTP Request, you will notice that only the Value for MyId is transferred at all. The target View Model, when reconstructed by the Model binder, will not populate MySelectList at all, when you see some data in it, that's probably because you're filling it again after the request.

You could, of course, easily perform the Update yourself:

var selectedItem = Model.MySelectList.FirstOrDefault(x => x.Value == Model.MyId);
if (selectedItem != null)
{
    selectedItem.Selected = true;
}

The question is, whether it helps for your further processing.

thmshd
  • 5,729
  • 3
  • 39
  • 67
  • thanks a lot. I put a break point in my model constructor and you are perfectly right, the select list item is not being passed in. – Hooman Bahreini Jul 23 '18 at 09:40