3
這讓我完全困惑。DropDownListFor SelectedItem問題
這是我的觀點:
@Html.DropDownListFor(model => model.ScoreDescription,
Model.RatingOptions,
"--",
new { @id = clientId })
和模型:
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;
}
}
由於意見建議,我不能得到所選擇的值發生。
這是否與我使用可空的decimal
這個事實有關?在那個循環之後,options
是正確的,因爲它正好有1個選項爲true的項目,所以看起來我做的是正確的事情。現在
,如果我使用一個不同SelectList
超載:
var selectedValue = Score.HasValue ? Score.Value.ToString("0") : string.Empty;
var selectList = new SelectList(options, "Value", "Text", selectedValue);
它的工作原理。爲什麼?起初,我認爲這可能是一個LINQ技巧(例如推遲執行),但我試圖強制.ToList()
,沒有什麼區別。
這就像設置Selected
屬性一樣,因爲您創建的SelectListItem
沒有任何效果,您可以使用 ctor參數在最後設置它。
任何人都可以對此有所瞭解嗎?
右鍵,所以基本上我的最後一句是正確的 - 在這種情況下,SelectListItem的Selected屬性是毫無意義的。乾杯。 – RPM1984 2011-05-05 06:36:26