我想从数据库中获取国家/地区列表并将其绑定到下拉列表

时间:2016-06-14 10:50:32

标签: c# asp.net-mvc

这是我的代码在向countrylist

添加listofcountries时给出错误

ERROR

  

system.collection.generic.list不能分配给参数类型   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;
}

2 个答案:

答案 0 :(得分:1)

直接返回代码生成的列表。无需将其添加到其他列表

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();
    }

}

答案 1 :(得分:0)

试试这个

 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();

返回计数;       }