Problem with DropDownListFor SelectedItem

This completely puzzled me.

Here is my view:

@Html.DropDownListFor(model => model.ScoreDescription, 
                               Model.RatingOptions, 
                               "--", 
                               new { @id = clientId })

And the model:

public decimal? Score { get; set; }
public SelectList RatingOptions
{ 
    get
    {
        var options = new List<SelectListItem>();

        for (var i = 1; i <= 5; i++)
        {
            options.Add(new SelectListItem
            {
                Selected = Score.HasValue && Score.Value == Convert.ToDecimal(i),
                Text = ((decimal)i).ToRatingDescription(ScoreFactorType),
                Value = i.ToString()
            });
        }

        var selectList = new SelectList(options, "Value", "Text");
            // At this point, "options" has an item with "Selected" to true.
            // Also, the underlying "MultiSelectList" also has it.
            // Yet selectList.SelectedValue is null. WTF?
        return selectList;
    }
}

As follows from the comments, I cannot get the selected value.

How does this relate to the fact that I'm using nullable decimal? After this loop, it is optionstrue that it has exactly 1 element with the choice of true, so it seems like I'm doing the right thing.

Now, if I use another overload SelectList:

var selectedValue = Score.HasValue ? Score.Value.ToString("0") : string.Empty;
var selectList = new SelectList(options, "Value", "Text", selectedValue);

It works. What for? At first I thought it might be a LINQ trick (e.g., delayed execution), but I tried to force .ToList()and there is no difference.

How to set a property Selectedwhen creating SelectListItemhas no effect, and you set it at the end using the SelectListctor parameter .

Can anyone shed some light on this?

+3
1

SelectList, , SelectListItem. IEnumerable. , Selected SelectListItem . , , ddl.

:

public int? Score { get; set; }
public SelectList RatingOptions
{ 
    get
    {
        var options = Enumerable.Range(1, 5).Select(i => new SelectListItem
        {
            Text = ((decimal)i).ToRatingDescription(ScoreFactorType),
            Value = ((decimal)i).ToString()
        });
        return new SelectList(options, "Value", "Text");
    }
}

Score Score :

@Html.DropDownListFor(
    model => model.Score, 
    Model.RatingOptions, 
    "--", 
    new { @id = clientId }
)
+4

All Articles