.Net MVC .Html.EnumDropDownListFor tutorial with examples

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
    }
    
 
We are nothing without our users ! You can help us offer even more high quality content. Please share our page !
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
4 + 5 =
 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2023 CodingFusion
75 Important SQL Server queries you should know