如何从DB设置SelectList值

时间:2014-10-18 10:55:44

标签: asp.net-mvc linq asp.net-mvc-4 selectlist

我有城市名称和车牌。车牌从1到100开始。

我想展示牌照的城市,如32,54,88,1,2,3,4,5 ...... 100

车牌32,54,88个城市是我国最多选择的城市,所以我想首先展示它们。

我的数据库架构是这样的:

  • LicencePlateId = 32,CityName =" City1"
  • LicencePlateId = 54,CityName =" City2"
  • LicencePlateId = 88,CityName =" City3"
  • LicencePlateId = 1,CityName =" ...."
  • LicencePlateId = 2,CityName =" ...."
  • LicencePlateId = 3,CityName =" ...."
  • LicencePlateId = 4,CityName =" ...."

我使用此代码从db获取所有城市。我没问题

List<CityVM> myCity= new List<CityVM>();
  myCity= CityBL.GetAllCities();

比我将城市添加到SelectList

 List<SelectListItem> cityList= new List<SelectListItem>();
    {
        for (var i = 1; i < myCity.Count + 1; i++)
        {
        cityList.Add(new SelectListItem { Text = myCity.FirstOrDefault(k => k.Id == i).Ad.ToString(), Value = i.ToString() });
        }

        cityList.Add(new SelectListItem { Text = "All Cities ", Value = "100" });
    }

但是当我看到View部分下拉列表就是这样:

  • LicencePlate = 1,CityName =&#34; .....&#34;
  • LicencePlate = 2,CityName =&#34; .....&#34;
  • LicencePlate = 3,CityName =&#34; .....&#34;

如何从LicencePlateId = 32开始?

1 个答案:

答案 0 :(得分:1)

尝试使用List<SelectListItem>List<CityVM>按照for的顺序将项目添加到foreach

for (int i = 0; i < myCity.Count - 1; i++)
{
    cityList.Add(new SelectListItem 
                 { 
                    Text = myCity[i].Ad.ToString(), 
                    Value = myCity[i].Id.ToString() 
                 });
}

cityList.Add(new SelectListItem { Text = "All Cities ", Value = "100" });