Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create a dropdownlist from an enum in ASP.NET MVC

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 347
    Comment on it

    Many times in an application we need to populate a dropdown list from enum.In the following article I will show how to implement the same using SelectListItem.

    First we create an enum, FileType, under the Models folder as shown below.

    namespace DropdownDemo.Models
    {
        public enum FileType
        {
            Excel=1,
            PDF=2,
            TXT=3 
    } }

    Now we create View (Index.cshtml) as below.

    @model DropdownDemo.Models.ActionModel
    @{
        ViewBag.Title = "Index";
    } 
    @Html.LabelFor(model=>model.ActionId)
    @Html.DropDownListFor(model=>model.ActionId, Model.ActionsList)
    

    Next we create a list from an enum and add a model as below.

    public class ActionModel
    {
        public ActionModel()
        {
            ActionsList = new List<SelectListItem>();
        }
        [Display(Name="Actions")]
        public int ActionId { get; set; }
        public IEnumerable<SelectListItem> ActionsList { get; set; }       
    }
    

    Lastly we create a controller action method in Action Controller (ActionController.cs) that returns a view that binds with the model.

        public ActionResult Index()
        {
            ActionModel model = new ActionModel();
            IEnumerable<FileType> fileTypes = Enum.GetValues(typeof(FileType)).Cast<FileType>();
            model.ActionsList = from file in fileTypes
                                select new SelectListItem
                                {
                                    Text = file.ToString(),
                                    Value = file.ToString()
                                };
            return View(model);
        }
    

    When the above code is executed the enum items will be populated in the dropdown.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: