list 将 IList<string> 转换为 MVC.SelectListItem 需要显式转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7393159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert IList<string> to MVC.SelectListItem needs explicit casting
提问by Tom Stickel
I am calling a project (WCF, but that shouldn't matter) that consumes a IList , with MVC 3 (which really should not matter either obviously) I want to convert a single column List of strings (IList which is just a list of Countries) into a List
我正在调用一个使用 IList 的项目(WCF,但这无关紧要),使用 MVC 3(这显然也不重要)我想转换单列字符串列表(IList 只是一个列表国家)进入列表
Hard Coded list I have done like this and they work fine:
硬编码列表我已经这样做了,它们工作正常:
public List<SelectListItem> mothermarriedatdelivery = new List<SelectListItem>();
mothermarriedatdelivery.Add(new SelectListItem() { Text = "Yes", Value = "1" });
However, now I am trying to convert this code:
但是,现在我正在尝试转换此代码:
public List<SelectListItem> BirthPlace { get; set; }
BirthPlace = new List<SelectListItem>();
GetHomeRepository repo = new GetHomeRepository();
BirthPlace = repo.GetCountries();
I need to implicitly convert from the List to SelectListItem, anyone do this? Yes.. I have search and found several examples, but none that really fit my specific need.
我需要从 List 隐式转换为 SelectListItem,有人这样做吗?是的..我搜索并找到了几个例子,但没有一个真正适合我的特定需求。
回答by Laurent le Beau-Martin
You can use LINQ as such:
您可以这样使用 LINQ:
BirthPlace = repo.GetCountries()
.Select(x => new SelectListItem { Text = x, Value = x })
.ToList();
Or I think you can just use one of SelectList's constructors:
或者我认为您可以只使用 SelectList 的构造函数之一:
public SelectList BirthPlace { get; set; }
BirthPlace = new SelectList(repo.GetCountries());
回答by Nelson
In Controller ,
在控制器中,
var result = proxy.GetAllLocations();
ViewBag.Area = result.Where(p => p.ParentId == null).Select(p => new SelectListItem { Text = p.LocationName, Value = p.LocationId.ToString() }).ToList();
ViewBag.Locations = result.Where(p => p.ParentId != null).Select(p => new SelectListItem { Text = p.LocationName, Value = p.LocationId.ToString() }).ToList();
return View();
In View ,
在视图中,
@Html.DropDownList("LocationName", ViewData["Area"] as IEnumerable<SelectListItem>)