ASP.NET MVC5 DROPDOWNLIST

时间:2017-11-23 10:27:10

标签: twitter-bootstrap view asp.net-mvc-5 html.dropdownlistfor

任何人都可以帮助我this。列表中的第一项始终为空,因此它不应该是这样的:

@Html.DropDownList("EMRecordType_", null, "", new { @class = "form-control" })

控制器中的代码:

ViewBag.EMRecordType_ = new SelectList(db.EMRecords, "EMRecordType_", "EMRecordType_");

2 个答案:

答案 0 :(得分:0)

我已经复制了你的问题它工作正常

@Html.DropDownList("EMRecordType_", null, null, new { @class = "form-control" })


 public ActionResult Demo()
    {
        try
        {
            List<DemoModel> li = new List<Models.DemoModel>()
        {
            new DemoModel { ID = "1" , Value = "DemoModel1"},
            new DemoModel { ID = "2" , Value = "DemoModel2"},
            new DemoModel { ID = "3" , Value = "DemoModel3"},
            new DemoModel { ID = "4" , Value = "DemoModel4"},
            new DemoModel { ID = "5" , Value = "DemoModel5"},
            new DemoModel { ID = "6" , Value = "DemoModel6"},
            new DemoModel { ID = "7" , Value = "DemoModel7"},
        };

            ViewBag.EMRecordType_ = new SelectList(li, "ID", "Value");

            return View();
        }
        catch (Exception)
        {
            throw;
        }
    }

输出

enter image description here

答案 1 :(得分:0)

据我所知,您想要添加一个空的默认值,例如&#34;请选择...&#34;到下拉列表。

尝试此操作以获得以下输出..

@Html.DropDownList("empRecordTypeDropDown", (IEnumerable<SelectListItem>)ViewBag.EMRecordType_, "Please Select", new {@class="form-control"})

Output

如果您想添加完全空选项,请使用

@Html.DropDownList("empRecordTypeDropDown", (IEnumerable<SelectListItem>)ViewBag.EMRecordType_, "", new {@class="form-control"})

and the output

  • 第一个参数采用非空字符串值,该值用作下拉列表的idname
  • 由于@Html.Dropdown需要System.Web.Mvc.SelectListItem的集合,因此您必须投射动态ViewBag