Problem com DropDownListFor SelectedItem
Isso me intrigou totalmente.
Aqui está o meu ponto de vista:
@Html.DropDownListFor(model => model.ScoreDescription,
Model.RatingOptions,
"--",
new { @id = clientId })
E o 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;
}
}
omo os comentários sugerem, não consigo que o valor selecionado aconteç
Tem algo a ver com o fato de eu estar usando um @ anulávdecimal
? Após esse loop,options
está correto, pois possui exatamente 1 item com select para true, então parece que estou fazendo a coisa cert
Agora, se eu usar umdiferent SelectList
sobrecarga:
var selectedValue = Score.HasValue ? Score.Value.ToString("0") : string.Empty;
var selectList = new SelectList(options, "Value", "Text", selectedValue);
Funciona. Por quê? No início, pensei que poderia ser um truque de LINQ (por exemplo, execução adiada), mas tentei forçar um.ToList()
e não há diferença.
É como definir oSelected
ao criar a propriedadeSelectListItem
não tem efeito e você o definiu no final usando oSelectList
arâmetro cto
Alguém pode lançar alguma luz sobre isso?