Hooman Bahreini
Hooman Bahreini

Reputation: 15559

Selected is not set to true when I select an item in DropDownList

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?

Upvotes: 0

Views: 54

Answers (1)

thmshd
thmshd

Reputation: 5847

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.

Upvotes: 1

Related Questions