问题
I am rendering a drop down list box using my enums and I only have 3 options, but for some reason it is displaying four. The top and default option is simply blank/empty and I want this removed. I want the top/default value to be 'Option1'.
Enums:
public enum EventType
{
[Display(Name = "Option 1")]
Option1,
[Display(Name = "Option 2")]
Option2,
[Display(Name = "Option 3")]
Option3
}
View:
@Html.EnumDropDownListFor(model => model.EventType, null, new { @id = "eventType", @class = "form-control" })
Thanks for your help.
回答1:
Your second parameter is the "Option Label" which is used to set the first item in the dropdown. From the documentation: "The text for a default empty item"
Use an overload that doesn't take in the option label:
@Html.EnumDropDownListFor(model => model.EventType, new { @id = "eventType", @class = "form-control" })
UPDATE
I just tried your code. When I do both:
@Html.EnumDropDownListFor(model => model.EventType, null, new { @id = "eventType", @class = "form-control" })
And
@Html.EnumDropDownListFor(model => model.EventType, new { @id = "eventType", @class = "form-control" })
I get:
The only time I get another option in the dropdown is when I pass in a string as the second parameter, such as "Select..."
Any chance you are doing something with javascript to add an item to the dropdown?
回答2:
I also had the same problem.Solved this starting enum from 0 not 1 .
public enum EventType
{
[Display(Name = "Option 1")]
Option1,
[Display(Name = "Option 2")]
Option2,
[Display(Name = "Option 3")]
Option3
}
@Html.EnumDropDownListFor(model => model.EventType,
new {@id = "eventType", @class = "form-control" })
回答3:
I spent some time getting the above to work and was unsuccessful.
I found an alternative way :
HTML:
@Html.DropDownList("types",
Helper.Gettypes(),
new { @class = "form-control", @title = "--- Choose ---" })
Code:
public static List<SelectListItem> Gettypes()
{
var enums = Enum.GetNames(typeof(WorkLogType)).ToList();
var selectLIst = enums.Select(x => new SelectListItem {Value = x, Text = x}).ToList();
return selectLIst;
}
来源:https://stackoverflow.com/questions/36158163/remove-blank-empty-entry-at-top-of-enumdropdownlistfor-box