C# 如何在asp.net mvc中选择一个选择列表项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1779741/
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
How to make a select list item selected in asp.net mvc?
提问by chobo2
I have the following code but it never selects the value I want.
我有以下代码,但它永远不会选择我想要的值。
List<SelectListItem> list = new List<SelectListItem>();
SelectListItem one = new SelectListItem() { Text = "MyTest", Value = "MyTest"};
SelectListItem two= new SelectListItem() { Text = "Test2", Value = "Test2" };
if (id == "MyTest")
{
one .Selected = true;
}
else
{
two.Selected = true;
}
list.Add(one);
list.Add(two);
ViewData["DDL"] = new SelectList(list, "value", "text");
So I am not sure what I am doing wrong
所以我不确定我做错了什么
in my view I have
在我看来我有
<%= Html.DropDownList("DDL") %>
采纳答案by LukLed
You should use:
你应该使用:
ViewData["DDL"] = new SelectList(list, "value", "text", id == "MyTest" ? "MyTest" : "Test2");
You should define selected value in SelectList constructor.
您应该在 SelectList 构造函数中定义选定的值。
EDIT
编辑
Answer to question:
回答问题:
You don't have to provide List to SelectList constructor. It can be collection of any object. You just have to provide key, value propery and selected value. Your code could also look like:
您不必向 SelectList 构造函数提供 List。它可以是任何对象的集合。您只需要提供键、值属性和选定的值。您的代码也可能如下所示:
var selectItems = new Dictionary<string, string> {{"MyTest", "MyTest"}, {"Test2", "Test2"}};
ViewData["DDL"] = new SelectList(selectItems, "Key", "Value", id == "MyTest" ? "MyTest" : "Test2");