MVC - Set selected value of SelectList

后端 未结 14 1170
后悔当初
后悔当初 2020-12-13 08:03

How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue;

SelectList selectList = new SelectList(items, \"I         


        
14条回答
  •  失恋的感觉
    2020-12-13 08:48

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

提交回复
热议问题