这个问题在这里已经有了答案:





MVC5 - How to set “selectedValue” in DropDownListFor Html helper

(4 个回答)


3年前关闭。



@Html.DropDownListFor(model => model.Status, new List<SelectListItem>
       { new SelectListItem{Text="Active", Value="True"},
         new SelectListItem{Text="Deactive", Value="False"}})

鉴于我正在使用这个 drop dowenlist 编码。我运行我的应用程序默认停用值显示在下拉列表框中。我要显示默认值 事件

最佳答案

像这样:

@Html.DropDownListFor(model => model.Status, new List<SelectListItem>
       { new SelectListItem{Text="Active", Value="True"},
         new SelectListItem{Text="Deactive", Value="False"}},"Select One")

如果您希望默认选择 Active 则使用 SelectedSelectListItem 属性:
@Html.DropDownListFor(model => model.Status, new List<SelectListItem>
           { new SelectListItem{Text="Active", Value="True",Selected=true},
             new SelectListItem{Text="Deactive", Value="False"}},"Select One")

如果使用 SelectList ,那么你必须使用 this overload 并指定 SelectListItem Value 要设置的属性选择:
@Html.DropDownListFor(model => model.title,
                     new SelectList(new List<SelectListItem>
  {
      new SelectListItem { Text = "Active" , Value = "True"},
      new SelectListItem { Text = "InActive", Value = "False" }
  },
    "Value", // property to be set as Value of dropdown item
    "Text",  // property to be used as text of dropdown item
    "True"), // value that should be set selected of dropdown
     new { @class = "form-control" })

关于c# - @Html.DropDownListFor 如何设置默认值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23799091/

10-13 08:00
查看更多