Here is an example of how to use the @Html.EnumDropDownListFor
helper method in ASP.NET MVC to create a dropdown list for an enumeration:
First, define an enumeration in your model:
public enum Gender
{
Male,
Female,
Other
}
In your view model, add a property of the enumeration type:
public class MyViewModel
{
public Gender SelectedGender { get; set; }
// ... other properties
}
In your view, use the @Html.EnumDropDownListFor
helper method to create the dropdown list:
@model MyViewModel
@Html.LabelFor(m => m.SelectedGender) @Html.EnumDropDownListFor(m => m.SelectedGender)
To retrieve the selected value in your controller action, you can use the ModelState
:
[HttpPost]
public ActionResult MyAction(MyViewModel viewModel)
{
if (ModelState.IsValid)
{
var selectedGender = viewModel.SelectedGender;
// Do something with the selected value
}
return View(viewModel);
}
Note: The EnumDropDownListFor
helper method uses the names of the enumeration values as the display text for the options and the values of the enumeration as the values for the options. You can add Display attribute to the enumeration value to customize the displayed text.
public enum Gender
{
[Display(Name = "Male")]
Male,
[Display(Name = "Female")]
Female,
[Display(Name = "Other")]
Other
}