在ASP.NET MVC中填充DropDownlist [英] populating a DropDownlist in ASP.NET MVC
问题描述
我正在学习ASP.NET MVC.在处理下拉列表时,我遇到了一个小问题.
I'm learning ASP.NET MVC. I had a small problem when dealing with dropdownlist.
这就是我在控制器中所做的
This is what I did in controller
List<Int32> myList = new List<Int32>();
var a = (from m in datacontext.services
select m.ServiceID);
myList = a.ToList();
ViewData["ServiceID"] = new SelectList((IEnumerable<SelectListItem>)
a.ToList(), "ServiceID", "ServiceID");
在视图中
@Html.DropDownListFor(model => model.ServiceID, ViewData["ServiceID"] as SelectList)
这会导致错误
无法转换类型为'System.Collections.Generic.List
1[System.Int32]' to type 'System.Collections.Generic.IEnumerable
1 [System.Web.Mvc.SelectListItem]'的对象."
Unable to cast object of type 'System.Collections.Generic.List
1[System.Int32]' to type 'System.Collections.Generic.IEnumerable
1[System.Web.Mvc.SelectListItem]'."
如何解决?
用查询处理下拉列表的最佳方法是什么?
What's the best way to deal with populating dropdownlist with a query?
推荐答案
强制转换中存在错误.
要解决此问题,您可以执行以下操作:
To fix you can do this:
var a = datacontext.services.Select(arg => new { ServiceID = arg.ServiceID }).ToList();
ViewData["ServiceID"] = new SelectList(a, "ServiceID", "ServiceID");
或者这个:
var a = datacontext.services.Select(arg => arg.ServiceID).ToList();
ViewData["ServiceID"] = new SelectList(a);
在您的代码中a
是整数列表.无法将其强制转换为SelectListItem
的列表.
In your code a
is the list of integers. It cannot be cast into the list of SelectListItem
.
旁注:
myList
变量未在您的代码中使用.
Side note:
myList
variable is not used in your code.
这篇关于在ASP.NET MVC中填充DropDownlist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!