Skip to main content

Posts

Showing posts from October, 2015

Dropdown List from object List in MVC View

In previous months, i have opportunity to play along with MVC after a while using EF Code First and MVC 5. So today the snippet about creating DropdownList from object List rather than List of SelectListItem let's say u have this Company Class [Key] public int CompanyId { get; set; } public string Name { get; set; } public string Code { get; set; } and u want to display dropdown list based on Code as Text and Id as Value in the View u create a SelectList based on that field @Html.LabelFor(model => model.Brand.Company, htmlAttributes: new { @class = "control-label col-md-2" }) @Html.DropDownList("selectedCompany", Model.Companies.Select(_ => new SelectListItem { Text = _.Code, Value = _.CompanyId.ToString(), Selected = _.CompanyId.ToString() == Model.Brand.Company.CompanyId.ToString() }) ) the Model is a simple ViewModel that have Brands and Brand object sorry for the format, can not make it right :D