0

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.

tony montana
  • 105
  • 1
  • 13

2 Answers2

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