我的 ASP.NET MVC SelectList 有什么问题?
我正在尝试使用 SelectList 我的视图之一,但它只是未正确填充。它获取了正确数量的条目 (4),但它们都读取了 System.Web.Mvc.SelectListItem
。我启动了代码的调试器,发现发生了一些奇怪的事情。我一定做错了什么,但我不太明白是什么。
来自 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);
以及来自 View 的代码:
<%= Html.DropDownList("Type",Model.DeviceTypes) %>
因此,当我在调试器中查看此代码时,sl IEnumerable 已正确构建。我可以看到其中的所有 4 个元素,以及正确的 Text 和 Value 属性值。然而,一旦我调用 SelectList 构造函数,如果我展开它包含的 IEnumerable,我会看到它有 4 个条目,但其中的所有数据都已丢失。 Text 设置为 System.Web.Mvc.SelectListItem
,值为 null
。
我尝试将 ToList()
调用更改为 ToArray()
,以及完全删除它。这并没有改变行为。
我在这里做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:划掉我的第一个答案。
您应该将 IEnumerable 列表(如果项目)传递给视图,而不是尝试在控制器中构造 Html 项目。
控制器代码:
视图代码:
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:
Code for View: