更新时间:2023-11-30 09:04:46
这往往难倒的人很多 - 显然路线图MVC 5包括更直观的DropDownList帮手
This tends to stump people a lot - apparently the roadmap for MVC 5 includes more intuitive DropDownList helpers.
当你这样做:
@Html.DropDownListFor(x => x.TimeOption ...)
...的HTML助手将在其权力的不的使用您的值设置为选择= TRUE
在的SelectList 。它会:
... the HTML helper will do everything in its power not to use the value you set to Selected = true
in your SelectList
. It will:
的ModelState
得到它 - 它不会对GET请求获得的ViewData code>得到它 - 它的将会的搞定,因为你有一个 TimeOption
你的模型属性。
ModelState
- which it won't get on the GET requestViewData
- 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.
所以,你的情况,它将使用 TimeOption
的当前值,您模型作为选择的值。这应该是罚款,因为这就是你想要在你的的SelectList
反正((INT)Model.TimeOption
),对吧?
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?
错误。因为它会的不的投你的财产(枚举
?),以 INT
像你一样。这将其转换为字符串。对于枚举
能够产生枚举的名字 - 例如 PastMonth
。如果 TimeOption
是一个自定义类你们的,这将是的结果的ToString()
。
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.
在短: SelectListItem.Selected
对助手没有影响。如果你的助手调用指定一个名称(无论是从字面上或通过拉姆达前pression),助手将在的ModelState
或使用任何的ViewData
使用该名称,并将其转换为字符串。
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.
在大多数情况下,这种情况与枚举。绕过它最简单的方法是使用枚举的名称,而不是它的INT再presentation,至于 SelectListItem
。
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
.