views:

78

answers:

1

I'm trying to use a SelectList one of my views, and its just not populating correctly. It gets the proper number of entries (4), but they all read System.Web.Mvc.SelectListItem. I fired up the debugger on the code, and saw some strangeness going on. I must be doing something wrong, but I don't quite see what.

Code from the ViewModel:

public SelectList DeviceTypes {get; private set;}
....
var device_types = DataTableHelpers.DeviceTypes(); 
IEnumerable<SelectListItem> sl = device_types.Select(
                      dt => new SelectListItem { Selected = (dt.DeviceType == 1),
                      Text = dt.Description, 
                      Value = dt.DeviceType.ToString() }).ToList();
DeviceTypes = new SelectList(sl);

And code from the View:

<%= Html.DropDownList("Type",Model.DeviceTypes) %>

So, when I look at this in the debugger, the sl IEnumerable is getting built correctly. I can see all 4 elements in there, with the proper Text and Value property values. Once I call the SelectList constructor however, if I expand the IEnumerable that it contains, I see that it has 4 entries, but all the data in them has been lost. The Text is set to System.Web.Mvc.SelectListItem, and the value is null.

Ive tried changing the ToList() call to a ToArray(), as well as removing it entirely. That didn't change the behaviour.

What am I doing wrong here?

+3  A: 

EDIT: Scratch my first answer.

You should be passing the IEnumerable list if items to the View, not trying to construct a Html item in the controller.

Code for controller:

public IEnumberable<YourModel> DeviceTypes {get; internal set;}
....
DeviceTypes = DataTableHelpers.DeviceTypes();

Code for View:

<%= Html.DropDownList("Type", from dt in Model.DeviceTypes
                              select new SelectListItem
                              {
                                  Text = dt.Description,
                                  Value = dt.DeviceType.ToString(),
                                  Selected = dt.DeviceType == 1
                              }) %>
John Gietzen
Yep, that did it, thanks. I think I see what I was doing wrong now, too.
Jeff Shattock