Set selected value in SelectList after instantiation

后端 未结 10 2019
长发绾君心
长发绾君心 2020-12-05 17:39

Am I right to think that there is no way to set the selected value in the C# class SelectList after it is created? Isn\'t that a bit silly?

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 18:04

    I needed a dropdown in a editable grid myself with preselected dropdown values. Afaik, the selectlist data is provided by the controller to the view, so it is created before the view consumes it. Once the view consumes the SelectList, I hand it over to a custom helper that uses the standard DropDownList helper. So, a fairly light solution imo. Guess it fits in the ASP.Net MVC spirit at the time of writing; when not happy roll your own...

    public static string DropDownListEx(this HtmlHelper helper, string name, SelectList selectList, object selectedValue)
    {
        return helper.DropDownList(name, new SelectList(selectList.Items, selectList.DataValueField, selectList.DataTextField, selectedValue));
    }
    

提交回复
热议问题