有什么不对我的ASP.NET MVC的SelectList? [英] What is wrong with my ASP.NET MVC SelectList?

查看:142
本文介绍了有什么不对我的ASP.NET MVC的SelectList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用的SelectList我的意见之一,它只是不正确填充。它得到的条目(4)适当数量,但他们都读 System.Web.Mvc.SelectListItem 。我启动了在code调试器,并看到一些奇异事情。我必须做一些错误的,但我不太明白。

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:

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 code:

And code from the View:

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

所以,当我在调试器中看到这一点,SL IEnumerable的是越来越正确建立。我可以看到所有4个元素在里面,用适当的文本和Value属性值。然而,一旦我把选择列表的构造函数,如果我展开它包含了IEnumerable,我看到它有4个条目,但在他们所有的数据已经丢失。文本设置为 System.Web.Mvc.SelectListItem 和值

香港专业教育学院试图改变了ToList()打电话到 ToArray的(),以及消除它完全。这并没有改变行为。

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

我在做什么错在这里?

推荐答案

编辑:划伤我的第一个答案

您应该传递,如果项目视图,而不是试图在控制器来构建一个HTML项目列表的IEnumerable

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

code的控制器:

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

code为浏览:

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

这篇关于有什么不对我的ASP.NET MVC的SelectList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆