1

I have a simple table called LookupTable with two fields: Id (int) and Description (nvarchar) that I want to use to populate a drop down list.

The following code gives me the error:

IEnumerable<SelectListItem> items = 
  _entities.LookupTable.Select(t=> new SelectListItem {Value = t.Id, 
                                                       Text = t.Description } );

I have a using System.Linq; statement already, and I get a runtime error if I try t.Id.ToString().

I must be missing something simple, right?

1 Answer 1

1

It is not clear from your question what is the type of _entities.LookupTable. If we suppose that it is some IQueryable<SomeModel> or IEnumerable<SomeModel> where SomeModel contains two properties Id and Description, you must ensure that you are properly converting those two values to string as the Value and Text properties of a SelectListItem are strings.

You may also try to eagerly execute the query by calling .ToString():

var items = _entities
    .LookupTable
    .ToList()
    .Select(t => new SelectListItem 
    {
         Value = t.Id.ToString(), // <-- notice that you might need a ToString if the Id property is integer 
         Text = t.Description 
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.