What is wrong with my ASP.NET MVC SelectList?

假装没事ソ 提交于 2019-12-24 01:43:14

问题


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?


回答1:


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
                              }) %>


来源:https://stackoverflow.com/questions/2082069/what-is-wrong-with-my-asp-net-mvc-selectlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!