'ASP MVC 5 @Html.EnumDropDownListFor Defaults to first Item
I have the following enum:
public enum EmploymentType
{
FullTime,
PartTime,
Contract
}
public class MyViewModel
{
public string searchTerm { get; set; }
public EmploymentType EmploymentType { get; set; }
}
public ActionResult Index(string searchTerm, string EmploymentType)
{
// some other stuff
var viewModel = new MyViewModel { SearchTerm = search };
return View(viewModel);
}
@Html.EnumDropDownListFor(m => m.EmploymentType, "", new { @class = "form-control" })
When I load the page the dropdown default to the first item FullTime instead of the empty option. I am not setting the default value in my controller so why does it default to the first item and how can i get it to default to the empty option value instead?
Solution 1:[1]
If you add an empty option to your enum, that is a guarantee:
public enum EmploymentType
{
[Display(Name = "< Select >")]
Select = 0,
FullTime = 1,
PartTime = 2,
Contract = 3
}
By its very nature, it will select the first item in the list, so adding a generic "select" option is a way to ensure there is a default item.
If you rely on order, I'd highly recommend assigning a value to the enum value, so the numbers don't shift if you convert it to the integer equivalent.
Solution 2:[2]
You must add numbers to your enum values, which are NOT 0. Then "Select an option" will show automatically, if you haven't assigned any into your model.
public enum EmploymentType
{
FullTime = 1,
PartTime = 2,
Contract = 3
}
Other answers here works as well, but contributes little bit more work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Brian Mains |
| Solution 2 | mr_city |
