Set selected value in SelectList after instantiation

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

    I think you can do this in the controller. If you are going to render a drop down list with name/ID StateCode, then you can set the selected state using this code after the SelectList is created:

    ViewData["StateCode"] = "VT";

    It seems that the drop down list HTML helper looks for a ViewData item with the same name as the drop down list that's being created.

    I don't think I like using this technique, but it does seem to work.

    I do agree that the SelectList class is a little weak at the moment. I'd like to be able to create a SelectList and then select a value later by either value or text.

提交回复
热议问题