초짜 IT보이 서바이벌 스토리/C#
[MVC] #DropdownList #드롭다운 리스트 만들기 #List<SelectListItem>
matrim
2019. 2. 23. 01:00
반응형
아래 내용은 List<SelectListitem> 을 활용한 dropdownlist 를 만듭니다.
그리고 데이터베이스에 없는 item 을 중간에 끼워넣을 수도 있습니다. 예) -- ALL --
- View 코드 : Razor
@Html.DropDownList("select_type", ViewBag.selectList as List<SelectListItem>,
new { @class = "form-control", @id="select_type"} )
- 만들어지는 html
<select class="form-control" id="select_type" name="select_type"><option value="999999">-- Show ALL --</option><option value="1">Choice 1</option><option value="2">Choice 1</option><option value="3">Choice 1</option></select>
- Controller 코드 : C#
public ActionResult Index(){var selectTypesFromDataBase = dbContext.GetSelectTypes(); //db 에서 Type 리스트를 들고 옵니다.List<SelectListItem> selectTypesList = selectTypesFromDataBase.Select(c=> new SelectListItem() {Text = c.desc,Value = c.id}).ToList();selectTypesList.Insert(0, new SelectListItem(){Text = "-- Show ALL --",Value = "999999"});ViewBag.selectList = selectTypesList;return View();}
반응형