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
        }

 

 

 

 

posted @ 2021-10-27 14:43  哈佛  阅读(167)  评论(0编辑  收藏  举报