netcore 开发问题整理(下拉框)
页面绑定
//第一条 无 如果后台绑定类型INT 会报错
@Html.DropDownList("Classify", (ViewBag.Classify), "无", new { @class = "form-control" }) 推荐使用 <select asp-for="Classify" name="Classify" asp-items="ViewBag.Classify" class="form-control"> <option value="0">无所属</option> </select>
后台数据绑定
public IActionResult Index() { ViewBag.Classify = GetClassifyList(); return View(); } /// <summary> /// 下拉框绑定 /// </summary> /// <returns></returns> public List<SelectListItem> GetClassifyList() { List<SelectListItem> list= new List<SelectListItem>(); list.Add(new SelectListItem("鞋", "1")); list.Add(new SelectListItem("衣", "2")); list.Add(new SelectListItem("日用", "3")); list.Add(new SelectListItem("厨房", "4")); return list; } /// <summary> /// 下拉框绑定 读取数据库 /// </summary> /// <returns></returns> public List<SelectListItem> GetClassifyList() { List<SelectListItem> list= (from x in Classify() select new SelectListItem { Text = x, Value = x }).ToList(); return list; }
页面直接绑定枚举
<select asp-for="Quantityunits" name="Quantityunits" asp-items="Html.GetEnumSelectList<EnumModel.EnumQuantityunits>()" class="form-control"> </select>
枚举类
/// <summary> /// 数量单位 /// </summary> public enum EnumQuantityunits { [Display(Name = "件")] [Description("件")] Piece = 1, [Display(Name = "瓶")] [Description("瓶")] Bottle = 2, [Display(Name = "打")] [Description("打")] Dozen = 3, [Display(Name = "箱")] [Description("箱")] Boxful = 4, [Display(Name = "千克")] [Description("千克")] KG = 5, [Display(Name = "克")] [Description("克")] G = 6 }