Bind dropdown list in MVC using ViewBag
First, write a function in your controller.
Below is the function you can use. Instead of a List, you may get items from SQL or any other sources that up to you.
private void GetItems()
List<string> items = new List<string>();
ViewBag.Items = items;
Now you must call GetItems() function in your view. See Below.
public ActionResult Index()
Below is the .cshtml code to represent dropdown list with items.
@Html.DropDownList(“Item Selection”, new SelectList(ViewBag.Items as System.Collections.IEnumerable))
Keep your eyes on SharePointCafe.Net for upcoming MVC blogs
You may also like below blogs –
- What is MVC Routing?
- How to add Constraints in MVC?
- Attribute Routing in MVC
- RenderBody() vs RenderSection()
- What is ViewStart.cshtml file?