CodeOnly CodeOnly - 10 months ago 47
ASP.NET (C#) Question

How to create dropdownlist in ASP.Net MVC

I have a query like bellow code I am new to ASP.Net MVC:

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


How to generate drop down list in view

my view code:

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


but I get errors


'SelectListItem' does not contain a constructor that takes 1 arguments

Answer Source

Please try code bellow this should work:

@Html.DropDownListFor(model => model.CompanyId, new SelectList(ViewBag.MyCompanies, "Id", "CompanyName"), "- Please Select -", new { @required = "required", @class = "form-control " })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download