Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net MVC, SelectLists, and LINQ

I am new to using the Html.DropDownList in the MVC framework and am having a hard time understading how to select the data out my database to bind to the DropDownList. Is there an easy way to return a bindable list (such as a SelectList) from a standard LINQ query?

like image 969
jimbo Avatar asked Oct 23 '09 19:10

jimbo


2 Answers

The SelectList constructor takes an IEnumerable so all you need to do is pass the LINQ query to the constructor like so

 var query = from c in customers
                        select c;

 var customerList = new SelectList(query, "CustomerId", "CustomerName"); 

You should do this in the Controller and have the SelectList in your ViewModel.

like image 133
willbt Avatar answered Nov 15 '22 22:11

willbt


You want to use the select keyword in the LINQ query:

var foo = new SelectList(from x in FooRepository.Items
                         select new SelectListItem { Text = x.Name, Value = x.Id });
like image 42
Chris Charabaruk Avatar answered Nov 15 '22 20:11

Chris Charabaruk