【问题标题】:List<SelectListItem> with selected SelectListItem is not selected in the ViewList<SelectListItem> 与选定的 SelectListItem 未在视图中选择
【发布时间】:2015-02-07 13:03:40
【问题描述】:

我有一个SelectedListItem 的列表,我将它从控制器发送到使用 ViewBag 进行查看。 List 中有一个具有selected = true 属性的SelectedListItem。

查看代码为:

@Html.DropDownListFor(model => model.Configuration, 
new SelectList(ViewBag.ListOfConfigValues,"Value", "Text"),
new { @class = "ddl", @id = "ddlForConfiguration"})

我还在model.Configuration 中传递了我想要显示为选中的值。

我知道我们可以将选定的索引与ValueText 一起传递。

在控制器中,我将ViewBag 设置为

ViewBag.ListOfConfigValues = defaultObj.configurationsList;
                return PartialView(detail);

configurationList如下

{Text = "Red", Value = "Color1", Selected = false},
{Text = "Blue", Value = "Color2", Selected = true},
{Text = "Green", Value = "Color3", Selected = false}

【问题讨论】:

  • 在您填充ViewBag.ListOfConfigValuesConfiguration 属性的位置显示控制器的代码。

标签: asp.net-mvc asp.net-mvc-4 selectlistitem


【解决方案1】:

将您选择的值设置为model.Configuration 属性。

DropDownListFor 仅适用于 selected = true 元素,前提是您的 Configuration 属性将是 Nullable 类型并且目前是 null,否则 DropDownListForConfiguration 属性值中设置选定值。

编辑:

你的selectListItem 应该是value = "Red" and text = "Red"

或者

Model.Configuration = "Color1"

DropDownListFor 设置值取决于Value 属性,而不是Text

【讨论】:

  • 你好 @Teo 实际上 Model.Configuration = "Red" 和 selectListItem value = "Color1" 和 text = "Red"。如果我也设置了 value = "Red",那么它一切正常。
  • 谢谢。我想我只能以这种方式实施。不舒服但还好。谢谢你的回答。
  • np,试试看,请说出你的最终结果。
  • 是的,它对我来说很好用。休息必须有一个选项来根据文本而不是值来设置所选项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 2017-05-30
  • 2020-09-25
  • 2015-09-08
  • 1970-01-01
  • 2018-01-27
相关资源
最近更新 更多