【发布时间】:2011-05-05 03:41:43
【问题描述】:
这让我很困惑。
这是我的观点:
@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;
}
}
正如 cmets 所建议的,我无法让选定的值发生。
这与我使用可为空的 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() 并没有区别。
就像在创建SelectListItem 时设置Selected 属性没有任何效果,而您在最后使用SelectList ctor 参数设置它。
有人能解释一下吗?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 drop-down-menu razor html.dropdownlistfor