Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

c# - DropDownListFor not respecting Selected property of SelectList

I have the following line of code:

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

The drop down is properly built, and Selected is indeed correct but MVC will not draw the drop down list with the correct item selected. The markup does not output a selected attribute on an option.

The output is rendered as:

<option value="0">Past Day</option>
<option value="1">Past Week</option>
<option value="2">Past Month</option>
<option value="3">Past Year</option>
<option value="4">Start of Time</option>

Yet if you look at the attached screenshot you can see it is correctly selected:

Watch list

This affects only GET, not POST. Ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 <select> values (because they're all integers), it decides not to make anything selected.

In short: SelectListItem.Selected has no effect on the helper. If your helper call specifies a name (either literally or through a lambda expression), the helper will use anything in ModelState or ViewData with that name, and convert it to a string.

In most cases this happens with enumerations. The easiest way to get around it is to use the enumeration's name, rather than its int representation, as the value for the SelectListItem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...