简体   繁体   English

默认情况下在SelectList中设置一个选定的值

[英]Set a selected value by default in SelectList

I want to set a selected value in my select list by default. 我想默认在我的选择列表中设置一个选择的值。

Here I have this select list : 这里有这个选择列表:

@{
    var selectList = new SelectList(
        new List<SelectListItem>
        {
        new SelectListItem {Text = "Google", Value = "Google", Selected = false},
        new SelectListItem {Text = "Other", Value = "Other" , Selected = true},
        }, "Value", "Text");


   var selectedValue = "Other";
}

Here I'am trying to set "Other" is selected by default but it is not working for me why ? 在这里,我尝试设置默认情况下选择“其他”,但是对我来说为什么不起作用?

Here the Dropdownlist: 这里是下拉列表:

@Html.DropDownList("ddlDropDownList", selectList, new { @class = "css-class" })

"Other" is not selected by default because you have not told the SelectList which option is selected. 默认情况下未选择“其他”,因为您尚未告知SelectList选择了哪个选项。 Variable selectedValue is assigned but used no where. 变量selectedValue已分配,但未在何处使用。

Simply, use this method signature 只需使用方法签名

public SelectList (
  System.Collections.IEnumerable items,
  string dataValueField, 
  string dataTextField, 
  object selectedValue);

So your code in view will be 所以您的代码将是

@{
        var selectList = new SelectList(
            new List<SelectListItem>
            {
               new SelectListItem {Text = "Google", Value = "Google", Selected = false},
               new SelectListItem {Text = "Other", Value = "Other" , Selected = true},
            }, "Value", "Text", "Other");

}

Pay attention that the last variable of the SelectList constructor is the selected value 请注意,SelectList构造函数的最后一个变量是所选值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM