C# MVC 使用@Html.DropDownList和SelectList做下拉选项注意事项

1、后端

 public ActionResult Form(string keyValue)
        {
            var ent = bll.GetEntity(keyValue);
            var data = data.Where(t => t.EnCode == "ContractType").Select(d=>new { Name=d.ItemName,Value=d.ItemValue });
            ViewBag.ContractType = new SelectList(data,"Value", "Name", ent!=null?ent.Type:1);
            return View(ent);
        }

2、前端

  @Html.DropDownList("Type", ViewBag.ContractType as SelectList,"请选择类型", new { @class = "form-control"})

注意:ViewBag.ContractType中的ContractType不要使用与字段名称(Type)一样的名称,否则编辑时默认值无法选中。

 

posted @ 2023-03-16 09:40  James·wang  阅读(187)  评论(0编辑  收藏  举报