We have a controller, CountryController with an action “Add”, and the related View “Add”, and we have a SQL Server table named “Countries” with an int “Id” field and a string “CountryName” field.
I get all database data from DbContext and EntityFramework 6, so all the tables are mapped in the context.
In our CountriesModel we have:
-
- public SelectedList Countries {get; set;}
In the controller, within the HttpGet Add action we populate the SelectedList from Context:
-
- model.Countries = new SelectList(context.Countries.ToList(), "Id", “CountryName");
Now we want to bind DropDownListFor with populated SelectedList property, so we can pass the model to View “Add”:
In the view Add we have:
- @model CountriesModel
-
- ….
-
- @Html.DropDownListFor(model=>model.Countries.SelectedValue, Model.Countries)
The result is a populated DropDownList.