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");
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?