问题
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;" })
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;" })
... or ...
@Html.EnumDropDownListFor(m => m.Foo, "whatever", new { @class = "input-block-level " + Model.FooThingType, autocomplete = "off", style = "width: 100px;" })
The enum itself:
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
}
回答1:
You have not shown you model, but clearly your property is nullable, i.e.
public SomeEnum? Foo { get; set }
which allows null
values, therefore the EnumDropDownListFor()
method generates a null
option so that it can be selected.
You can either make the property not nullable (which will remove the null
option)
public SomeEnum Foo { get; set }
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 }
and in the view add
@Html.EnumDropDownListFor(m => m.Foo, new { ... })
@Html.ValidationMessageFor(m => m.Foo)
来源:https://stackoverflow.com/questions/48269607/remove-blank-entry-from-enumdropdownlistfor