MVC6 Dropdownlist of Countries
public class MyViewModel //MODEL LAYER
{
public int CountryId { get; set; }
public string CountryName { get; set; }
public List<Employee> EmployeesList { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string FullName { get; set; }
}
public IActionResult Contact1() //CONTROLLER
{
MyViewModel N1 = new MyViewModel();
List<Employee> N2 = new List<Employee>()
{
new Employee { Id=1,FullName="sivaragu" },
new Employee { Id=2,FullName="siva" },
new Employee { Id=3,FullName="SENTHIL" }
};
ViewBag.MovieType = N2;
return View();
}
CSHTML(MVC6)
<select asp-for="CountryId" asp-items="@(new SelectList(@ViewBag.MovieType,"Id","FullName") )">
</select>
The way I make my dropdowns is somewhat similar except that in my ViewModel, my property is of type SelectList
instead of an IEnumerable<>
.
public class HomeViewModel
{
public string CountryCode { get; set; }
public SelectList CountryList { get; set; }
}
Then in the controller I get the data and convert it to an anonymous list with two properties “Id” and “Value”.
In turn, I create a new SelectList()
passing in the anonymous list specifying what is the dataValueField
and what is the dataTextField
.
public IActionResult Index()
{
var countries = _customersContext.Countries.OrderBy(c => c.CountryName).Select(x => new { Id = x.Code, Value = x.Name });
var model = new HomeViewModel();
model.CountryList = new SelectList(countries, "Id", "Value");
return View(model);
}
Finally, in the View:
<div class="form-group">
<label asp-for="CountryCode" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="CountryCode" asp-items="@Model.CountryList"></select>
</div>
</div>