Set selected value in SelectList after instantiation

后端 未结 10 2037
长发绾君心
长发绾君心 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:16

    I agree with @awrigley and others that it is better to load the selected value using the selectlist constructor in the usual case when you have a single dropdownlist. However, sometimes, one needs to set the selected value on the view, such as when you have a page with n identical dropdowns. Since it is not practical to create such collections in the controller and may not even know in advance how many dropdowns you need, a better approach is to create one instance in the viewmodel as a template with no selected value set and then dynamically create the rest dynamically on the view.

    I run into this often when iterating through a list of child items on edit views when the children need dropdowns. In such cases, you can do it like this with one line of code:

    @Html.DropDownListFor(x => myViewModelFieldName, new SelectList(Model.MyRawSelectListFromMyViewModel.Select(x=> new {x.Value, x.Text}), "Value", "Text", TheValueYouWantToSelect))
    

提交回复
热议问题