MVC DropdownList 怎么绑定数据库中的值


1.从数据库读取数据

   List<GetCitInfo> modelcitys = new List<GetCitInfo>();
            modelcitys = hpmDal.GetlistCityInfo();

2.将数据读取过来之后  存在modelcitys 集合中

3.实例化一个SelectListItem 

  List<SelectListItem> itemList = new List<SelectListItem>();


3.遍历所有的数据

 foreach (var t in modelcitys)
            {
                var itemselectLanguage = new SelectListItem { Value = t.cityID.ToString(), Text = t.citiName };
                if (t.cityID == model.cityId)
                {
                    itemselectLanguage.Selected = true;
                }


                itemList.Add(itemselectLanguage);
            }

4.将集合放到ViewData 中

   ViewData["cityId"] = itemList;

5.页面显示

   @Html.DropDownList("cityId", null, new { style = "" })     

结束。下次可以直接抄了  




猜你喜欢

转载自blog.csdn.net/ypz131023/article/details/75447474