Tutorial Populate ASP.NET MVC Dropdownlist with ViewBag and Model values
Last Updated: June 7, 2021Sometimes it our ASP.NET MVC application it becomes necessary to populate dropdown with dynamic values such as from the database. So here in the controller you can create a list object of type SelectListItem, fill it with values and then send this object to the View.
Binding DropDownList with ViewBag
Lets take a simple example of filling a dropdown list with different states of America. In the controllers action create a list object of type SelectListItem, add some items to it. Finally send this list object to the View using a ViewBag object. Check the below code:
Controller
View
In the View I simply bind the DropDownList with the ViewBag variable. In this way the dropdownlist gets populated with the dynamic values returned from the controllers action method.
Binding DropDownList from Model
Suppose I have to bind DropDownList from the Model which in my case is the marks of a student in different subjects.
So add a Model class called Marks.cs with the following code.
In the controller create an array of Model Class object and return it to View.
In the View simply use the Html.DropDownListFor[] helper. In its second parameter pass a SelectList object that should contain 3 things:
- 1. Model
- 2. DataValueField
- 3. DataTextField
Note: Use .Concat[] method to add initial value [Text=All & Value=All] to dropdownlist like:
Binding DropDownList from Model List
You can also pass List of class objects to the View and bind the DropDownList with them. In the same example I can create a List object in the action method and return it to the View.
Finally in the View do like this:
I have written 2 very useful tutorial on Validation in ASP.NET MVC. You should check them:
1. Server Side Validation in ASP.NET Core
2. Client Side Validation in ASP.NET Core