Alternatex
Alternatex

Reputation: 1552

Razor DropDownListFor sets selected value when I have no value set

I have three DropDownListFor helpers in my view. All three of them use the same List<SelectListItem> as their 'options' parameter. The 1st and 3rd DropDownListFor contain an integer value that comes from my Model and the 2nd DropDownListFor has a null value coming from my Model. Naturally, I'd expect the 2nd dropdown list to have no option selected and fall back to its default 'Please select' option. But this doesn't happen. Every time I send a null value to the 2nd dropdown, it gets set to the same selected option as the one before it (the 1st one).

Here's what my simplified code looks like:

<div class="form-group">
    @Html.LabelFor(m => m.FirstId)
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.FirstId, Model.SelectOptions, "Please select")
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.SecondId)
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.SecondId, Model.SelectOptions, "Please select")
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.ThirdId)
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.ThirdId, Model.SelectOptions, "Please select")
    </div>
</div>

The only difference in the Ids is that the 1st and 3rd are int and the 2nd is a nullable int. Any ideas why this is happening?

EDIT:

Here's how I'm constructing my SelectOptions:

model.SelectOptions.AddRange(db.SelectOptions.ToList().Select(option => new SelectListItem { Text = option.Name, Value = option.Id.ToString() }));

Upvotes: 3

Views: 8108

Answers (1)

mask8
mask8

Reputation: 3638

Since your code for view shares Model.SelectOptions object by three dropdowns, the Selected property on each SelectListItem object in the list may be interfered.

In your example, when first dropdown is constructed, one of SelectListItem object of which value matches Model.FirstId value will be set to true. On second dropdown creation, as Model.SecondId is null which does not exist in Model.SelectOptions list, SelectListItem with Selected=True will continue to be selected. Then third dropdown, since the Model.ThirdId has value that exists in the list, again the Selected property of SelectListItem with the value will turn to true and selected.

In order to resolve this, I would pass new SelectList object to each DropDown:

@Html.FropDownListFor(m => m.FirstId, new SelectList(Model.SelectOptions, "Value", "Text"), "Please Select")
@Html.FropDownListFor(m => m.SecondId, new SelectList(Model.SelectOptions, "Value", "Text"), "Please Select")
@Html.FropDownListFor(m => m.ThirdId, new SelectList(Model.SelectOptions, "Value", "Text"), "Please Select")

Assuming none of SelectListItem.Selected in Model.SelectOptions is set to true.

Upvotes: 4

Related Questions