Problem with DropDownListFor SelectedItem

房东的猫 提交于 2019-12-01 20:19:22

If you look at the implementation of the SelectList class it never actually uses the fact that you are passing a SelectListItem. It works with an IEnumerable. So the Selected property of a SelectListItem is not used. Personally I prefer setting the selected value of a dropdown by setting the value of the corresponding property that you are binding the ddl to.

Example:

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");
    }
}

and then in the controller action simply set the Score property to the necessary value and in the view use this Score property to bind to:

@Html.DropDownListFor(
    model => model.Score, 
    Model.RatingOptions, 
    "--", 
    new { @id = clientId }
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!