3

这完全让我感到困惑。

这是我的观点:

@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;
    }
}

正如评论所暗示的,我无法让选定的值发生。

这与我使用 nullable 的事实有关decimal吗?在那个循环之后,options它是正确的,因为它恰好有 1 个选择为 true 的项目,所以看来我在做正确的事情。

现在,如果我使用不同 SelectList的重载:

var selectedValue = Score.HasValue ? Score.Value.ToString("0") : string.Empty;
var selectList = new SelectList(options, "Value", "Text", selectedValue);

有用。为什么?起初我认为这可能是一个 LINQ 技巧(例如延迟执行),但我尝试强制 a.ToList()并且没有区别。

这就像在Selected创建时设置属性SelectListItem没有效果,并且您在最后使用SelectListctor 参数设置它。

任何人都可以对此有所了解吗?

4

1 回答 1

4

如果您查看 SelectList 类的实现,它实际上从未使用过您传递SelectListItem. 它与IEnumerable. 所以没有使用Selecteda 的属性。SelectListItem就我个人而言,我更喜欢通过设置将 ddl 绑定到的相应属性的值来设置下拉列表的选定值。

例子:

public int? Score { get; set; }
public SelectList RatingOptions
{ 
    get
    {
        var options = Enumerable.Range(1, 5).Select(i => new SelectListItem
        {
            Text = ((decimal)i).ToRatingDescription(ScoreFactorType),
            Value = ((decimal)i).ToString()
        });
        return new SelectList(options, "Value", "Text");
    }
}

然后在控制器操作中简单地将Score属性设置为必要的值,并在视图中使用此 Score 属性绑定到:

@Html.DropDownListFor(
    model => model.Score, 
    Model.RatingOptions, 
    "--", 
    new { @id = clientId }
)
于 2011-05-05T06:33:07.137 回答