问题描述
我找到了一些S.O.有关此问题的帖子,但没有一个对我有用的答案。我正在使用枚举
创建一个 EnumDropDownListFor
,它正在工作,但我不想在顶部输入空白的下拉菜单。我希望用户被迫接受枚举
中的一项。代码如下:
I found a few S.O. posts regarding this problem, but none of the accepted answers worked for me. I am using an enum
to create an EnumDropDownListFor
and it's working, but I do not want a blank entry at the top of the drop-down. I want the user to be forced to accept one of the items from the enum
. Code follows:
@Html.EnumDropDownListFor(m => m.Foo, new { @class = "input-block-level " + Model.FooThingType, autocomplete = "off", style = "width: 100px;" })
注意上述内容,我已经根据其他方法中的公认答案尝试了几种方法帖子,包括在 EnumDropDownListFor(...)
调用中添加和删除各种参数。这只会导致编译时错误,主要是没有EnumDropDownListFor()版本使用 n 自变量错误。例如:
Note on the above, I have tried several variants of this based on the accepted answers in other S.O. posts, including adding and removing a variety of arguments in the EnumDropDownListFor(...)
call. This results only in compile time errors, mostly "no version of EnumDropDownListFor() takes n arguments" errors. E.g.:
@Html.EnumDropDownListFor(m => m.Foo, null, new { @class = "input-block-level " + Model.FooThingType, autocomplete = "off", style = "width: 100px;" })
...或...
@Html.EnumDropDownListFor(m => m.Foo, "whatever", new { @class = "input-block-level " + Model.FooThingType, autocomplete = "off", style = "width: 100px;" })
枚举本身:
public enum SomeEnum
{
[Description("Thingie")]
Thingie,
[Description("AnotherThingie")]
AnotherThingie,
[Description("LastThingie")]
LastThingie
}
我也尝试过此操作,但是没什么区别。
I also tried this, but it made no difference:
public enum SomeEnum
{
[Description("Thingie")]
Thingie = 0,
[Description("AnotherThingie")]
AnotherThingie = 1,
[Description("LastThingie")]
LastThingie = 2
}
推荐答案
您尚未显示模型,但显然您的资产为空,即
You have not shown you model, but clearly your property is nullable, i.e.
public SomeEnum? Foo { get; set }
允许 null
值,因此 EnumDropDownListFor()
方法生成一个 null
选项,以便可以选择它。
which allows null
values, therefore the EnumDropDownListFor()
method generates a null
option so that it can be selected.
您可以使属性不可为空(这将删除 null
选项)
You can either make the property not nullable (which will remove the null
option)
public SomeEnum Foo { get; set }
或更好,将其保留为空并添加 [Required]
属性可强制用户进行选择,以防止发布不足的攻击(请参阅以获取详细说明)
or better, leave it nullable and add the [Required]
attribute to force the user to make a selection which protects against under-posting attacks (refer What does it mean for a property to be [Required] and nullable? for a detailed explanation)
[Required(ErrorMessage = "Please select a ... ")]
public SomeEnum Foo { get; set }
并在视图中添加
@Html.EnumDropDownListFor(m => m.Foo, new { ... })
@Html.ValidationMessageFor(m => m.Foo)
这篇关于从EnumDropDownListFor(...)删除空白条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!