dropdown list in mvc code example

Example 1: drop down list mvc5

@Html.DropDownList("MySkills", (IEnumerable  
        <SelectListItem>)ViewBag.MySkills)

Example 2: razor dropdownlistfor

@using MyMVCApp.Models

@model Student

@Html.DropDownListFor(m => m.StudentGender, 
            new SelectList(Enum.GetValues(typeof(Gender))), 
            "Select Gender")

Example 3: how to use dropdownlist in mvc

BY LOVE
1-	Create a simple method to get the dropdown value

public List<SelectListItem> GetCategories()
        {
            var ResultCategory = objRKMGEntities.Categories.ToList();
            List<SelectListItem> listCategories = new List<SelectListItem>();
            foreach (var items in ResultCategory)
            {
                listCategories.Add(new SelectListItem() { Text = items.Category_Name, Value = items.Category_Id.ToString() });
            }
            return listCategories;
        }

2-	Call the GetCategories() in action method and store the data in viewbag.

public ActionResult SubCategory()
        {
            ViewBag.Categories = GetCategories();
            return View();
        }

3-	Use the viewbag object in the dropdownlist of the view

@Html.DropDownList("CategoryId", ViewBag.Categories as List<SelectListItem>, "Select Category")

Tags:

Html Example