如何在ASP.Net MVC中创建下拉列表

时间:2017-08-17 05:12:17

标签: c# asp.net asp.net-mvc asp.net-mvc-5

我有一个类似于下面的代码的查询我是ASP.Net MVC的新手:

 var MyCompanies = _context.MyCompanyInfoContext.Where(u => u.UserId == user.Id).OrderBy(o => o.CompanyName);

如何在视图中生成下拉列表

我的观看代码:

@Html.DropDownListFor(model=>model.CompanyId, new SelectListItem(ViewBag.MyCompanies))

但我收到错误

  

'SelectListItem'不包含带有1个参数的构造函数

1 个答案:

答案 0 :(得分:2)

请尝试以下代码:

@Html.DropDownListFor(model => model.CompanyId, new SelectList(ViewBag.MyCompanies, "Id", "CompanyName"), "- Please Select -", new { @required = "required", @class = "form-control " })