c# 中的 SelectList 类是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18081030/
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
What is the SelectList class in c#?
提问by spiderplant0
I'm trying to understand c# ASP.NET MVC4 and keep coming across SelectList. I can't seem to find an explanation of what it is, other that this:
我正在尝试了解 c# ASP.NET MVC4 并不断遇到SelectList. 我似乎无法找到它是什么的解释,除此之外:
http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist%28v=vs.108%29.aspx
http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist%28v=vs.108%29.aspx
Can anyone give a simple explanation of it, and show how to use it?
谁能给它一个简单的解释,并展示如何使用它?
采纳答案by Mojtaba
There is a simple code that I used for dropdownlist in asp.net mvc:
我在asp.net mvc 中有一个用于下拉列表的简单代码:
In Controller:
在Controller:
List<SelectListItem> dropdownItems = new List<SelectListItem>();
dropdownItems.AddRange(new[]{
new SelectListItem() { Text = "Option One", Value = "1" },
new SelectListItem() { Text = "Option Two", Value = "2" },
new SelectListItem() { Text = "Option Three", Value = "3" }});
ViewData.Add("DropDownItems", dropdownItems);
And, in cshtmlview:
并且,cshtml鉴于:
@Html.DropDownList("Types", ViewData["DropDownItems"] as List<SelectListItem>)
@Html.ValidationMessageFor(model => model.Types)
回答by Selva
SelectListclass which contains the Key, Value pair with the Selected item to True.
SelectList类,其中包含 Key、Value 对,其中 Selected 项为 True。
For Example,
例如,
listItems.Add(new SelectListItem
{
Text = xElement.Element("text").Value,
Value = xElement.Element("value").Value
});
var selected = listItems.Where(x => x.Value == "Test1").First();
selected.Selected = true;
This sample which helps to get the selected value in dropdownlist.
此示例有助于获取dropdownlist 中的选定值。
回答by Abbas Amiri
Working with drop-down lists in ASP.NET MVC has some confusing aspects, it's the reason that you find some classes that help developers to work with this prevalent object.
在 ASP.NET MVC 中使用下拉列表有一些令人困惑的方面,这就是您找到一些帮助开发人员使用这个流行对象的类的原因。
There is a great blog-post which I think describes SelectList clearly.
有一篇很棒的博客文章,我认为它清楚地描述了 SelectList。
http://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx
http://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx

