SelectList And DropDownList

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:

  1. // within the model  
  2. public SelectedList Countries {getset;}  
In the controller, within the HttpGet Add action we populate the SelectedList from Context:
  1. // within the controller  
  2. 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:
  1. @model CountriesModel  
  2.   
  3. ….  
  4.   
  5. @Html.DropDownListFor(model=>model.Countries.SelectedValue, Model.Countries)  
The result is a populated DropDownList.