.net MVC, SelectLists, and LINQ
Asked Answered
M

3

8

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?

Mcginn answered 23/10, 2009 at 19:58 Comment(0)
C
12

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.

Copyist answered 23/10, 2009 at 20:23 Comment(0)
L
8

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 });
Les answered 23/10, 2009 at 20:23 Comment(1)
This does not work for me. I try to iterate the resulting SelectList as decsribed here and get only System.Web.Mvc.SelectListItem as text and null as value.Wills
T
0
    var foo = FoorePository.Items.Select(s = > new SelectListItem 
                                        {
                                          Text = s.Name, Value = s.Id.ToString()
                                        }
);

Sorry about formatting.

Tolkan answered 21/10, 2014 at 11:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.