DropDownListFor not respecting Selected property of SelectList

前端 未结 2 1304
北海茫月
北海茫月 2020-12-17 19:37

I have the following line of code:

@Html.DropDownListFor(x => x.TimeOption, new SelectList(Model.TimeOptions, \"Value\", \"Name\", (int)Model.TimeOption))         


        
2条回答
  •  半阙折子戏
    2020-12-17 20:24

    This tends to stump people a lot - apparently the roadmap for MVC 5 includes more intuitive DropDownList helpers.

    When you do:

    @Html.DropDownListFor(x => x.TimeOption ...)
    

    ... the HTML helper will do everything in its power not to use the value you set to Selected = true in your SelectList. It will:

    • Try to get it from ModelState - which it won't get on the GET request
    • Try to get it from ViewData - which it will get, because you have a TimeOption property on your model.

    Only if both of those attempts fail, will it succumb, and use what you asked it to use.

    So, in your case, it will use the current value of TimeOption on your model as the selected value. Which should be fine, because that's what you asked for in your SelectList anyway ((int)Model.TimeOption), right?

    Wrong. Because it will not cast your property (enum?) to int like you do. It will convert it to a string. For an enum that yields the enumeration's name - e.g. PastMonth. If TimeOption is a custom class of yours, it will be the result of ToString().

    Then, when it doesn't find that string as one of your

    提交评论

提交回复
热议问题