Where to load dropdown list of country list in MVC Asp.net? Should we populate the dropdown in controller or in model itself? Any example.
Asked
Active
Viewed 34 times
0
-
You might wanna search SO first. https://stackoverflow.com/questions/18382311/populating-a-razor-dropdownlist-from-a-listobject-in-mvc – Mad Dog Tannen Jan 24 '19 at 13:36
-
I would always suggest to populate the dropdown in the controller – JamesS Jan 24 '19 at 14:20
2 Answers
0
you should pass the list to view model from controller action and populate it in the razor view.you can find more at the following link http://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor

Usama Kiyani
- 195
- 10
0
It depends, for example if you store countries in your database, its probably better to build the SelectList in your controller action:
public ActionResult Index()
{
var countries = db.Countries.ToList(); // get your countries
var model = new CountryViewModel();
model.Countries = new SelectList(countries,"Id","Name");
return View(model);
}
I guess your CountryViewModel
can look like this:
public class CountryViewModel{
public SelectList Countries {get;set;}
public int CountryId {get;set;}
}
Then in your view you can show the DropDown:
@Html.DropDownListFor(model => model.CountryId, Model.Countries, htmlAttributes: new { @class = "form-control" })
If it is a static list you can populate it in the model itself:
public class CountryViewModel{
public SelectList Countries {get;set;}
public int CountryId {get;set;}
public CountryViewModel{
Countries = new SelectList(GetCountriesFormSomeGlobalPlace(),"Id","Name");
}
}
Generally, do not use your code first models in your views (if you are using code first that is), but rather use ViewModel
POCOs
.

JustLearning
- 3,164
- 3
- 35
- 52