Problema con DropDownListFor SelectedItem
Esto me ha desconcertado totalmente.
Aquí está mi vista:
@Html.DropDownListFor(model => model.ScoreDescription,
Model.RatingOptions,
"--",
new { @id = clientId })
Y el modelo:
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;
}
}
Como sugieren los comentarios, no puedo obtener el valor seleccionado.
Tiene algo que ver con el hecho de que estoy usando un @ anulabldecimal
? Después de ese ciclo,options
es correcto porque tiene exactamente 1 elemento con select to true, por lo que parece que estoy haciendo lo correcto.
Ahora, si uso undiferent SelectList
sobrecarga:
var selectedValue = Score.HasValue ? Score.Value.ToString("0") : string.Empty;
var selectList = new SelectList(options, "Value", "Text", selectedValue);
Funciona. ¿Por qué? Al principio pensé que podría ser un truco LINQ (por ejemplo, ejecución diferida), pero intenté forzar un.ToList()
y no hay diferencia.
Es como configurar laSelected
propiedad mientras crea laSelectListItem
no tiene ningún efecto, y tienes que configurarlo al final usando elSelectList
parámetro ctor.
¿Alguien puede arrojar algo de luz sobre esto