mvc core dropdownlistfor code example
Example 1: mvc 5 dropdownlist
//To populate DropDownList using Viewbag, let's create some collection list with
//selectListItem types and assign to the Viewbag with appropriate name:
public ActionResult Index() {#
region ViewBag
List < SelectListItem > mySkills = new List < SelectListItem > () {
new SelectListItem {
Text = "ASP.NET MVC", Value = "1"
},
new SelectListItem {
Text = "ASP.NET WEB API", Value = "2"
},
new SelectListItem {
Text = "ENTITY FRAMEWORK", Value = "3"
},
new SelectListItem {
Text = "DOCUSIGN", Value = "4"
},
new SelectListItem {
Text = "ORCHARD CMS", Value = "5"
},
new SelectListItem {
Text = "JQUERY", Value = "6"
},
new SelectListItem {
Text = "ZENDESK", Value = "7"
},
new SelectListItem {
Text = "LINQ", Value = "8"
},
new SelectListItem {
Text = "C#", Value = "9"
},
new SelectListItem {
Text = "GOOGLE ANALYTICS", Value = "10"
},
};
ViewBag.MySkills = mySkills;#
endregion
return View();
}
//And now bind the ViewBag.MySkills values to DropDownlist as below code in view:
<tr>
<td> Populating With ViewBag Data </td>
<td> @Html.DropDownList("MySkills", (IEnumerable
<SelectListItem>)ViewBag.MySkills) </td>
</tr>
Example 2: 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")