Asp.net-Mvc
.net MVC、SelectLists 和 LINQ
我是在 MVC 框架中使用 Html.DropDownList 的新手,並且很難理解如何從我的數據庫中選擇數據以綁定到 DropDownList。有沒有一種簡單的方法可以從標準 LINQ 查詢中返回可綁定列表(例如 SelectList)?
SelectList 建構子採用 IEnumerable,因此您只需將 LINQ 查詢傳遞給建構子,如下所示
var query = from c in customers select c; var customerList = new SelectList(query, "CustomerId", "CustomerName");您應該在 Controller 中執行此操作,並在 ViewModel 中有 SelectList。
您想
select在 LINQ 查詢中使用關鍵字:var foo = new SelectList(from x in FooRepository.Items select new SelectListItem { Text = x.Name, Value = x.Id });