简体   繁体   中英

I want to get list of countries from database and bind it to dropdown list

Here is my code gives me error while add countrylist to listofcountries

ERROR

system.collection.generic.list is not assignable to parameter type system.web.mvc.selectListitem

CODE

public List<SelectListItem> Getallcountries()
{
    var listofcountries = new List<SelectListItem>();
    using (var db = new DatabaseContext())
    {
        var countrylist = db.Countries.Where(x => x.IsActive == true).ToList().Select(x => new SelectListItem
        {
            Text = x.CountryName,
            Value = Convert.ToString(x.ID)
        });

       listofcountries.Add(countrylist);
    }
    return listofcountries;
}

Return the list generated by code directly. No need to add it to another list

public List<SelectListItem> Getallcountries()
{

    using (var db = new DatabaseContext())
    {
        var countrylist = db.Countries.Where(x => x.IsActive == true).ToList().Select(x => new SelectListItem
        {
            Text = x.CountryName,
            Value = Convert.ToString(x.ID)
        });

       return  countrylist.ToList();
    }

}

Try This

 using(var db=new dbContect()
  {
      var count=db.Countries.Where(x=>x.IsActive==true).Select(a=>new SelectListItem{
    Text=a.CountyName,
    Value=SqlFunctions.StringConvert(a.ID)
}).ToList();

return count; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM