我正在使用DropDownListFor
在视图中呈现下拉列表。以某种方式,呈现的列表不会选择SelectListItem
Selected
设置为true
。
在控制器操作中:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Selected = entry.Value.Equals(selectedValue),
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = id,
SelectList = selectList,
OptionLabel = "Click to Select"
});
在视图中:
<%= Html.DropDownListFor(m => m.ListId,
Model.SelectList,
Model.OptionLabel,
new {@class="someClass"}) %>
我尝试了以下内容:
Selected
项设置为true
的项目。SelectList
中使用DropDownListFor
: Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {@class="someClass"})
关于出了什么问题的任何建议?
修改:
更多信息:
HTML.RenderAction
答案 0 :(得分:6)
DropDownListFor将始终选择列表框所用的值,因此在这种情况下,它将查看ListId的值并在列表中选择该项。如果未在列表中找到ListId,则将选择第一个项目(或默认文本)。如果你想要一个基于所选属性选择的列表,请使用DropDownList(没有For,在这种情况下你必须自己命名)。
所以在你的情况下,这将起作用:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
答案 1 :(得分:5)
我在同一个模型上遇到了同样的问题(决定中的其他模型没有问题)
不起作用:
@Html.DropDownListFor(o => o.Drivers.ValueListItems.Value, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
完美运作,所选元素:
@Html.DropDownListFor(o => o.Drivers.ValueListItems.ToDictionary(u=>u.Value).Values, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
答案 2 :(得分:4)
试试这样:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
// The drop down list is bound to ListId so simply set its value
// to some element value in the list and it will get automatically
// preselected
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
并在视图中:
<%= Html.DropDownListFor(
m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text"),
Model.OptionLabel,
new { @class = "someClass" }
) %>
可能还有一个问题:您正在尝试更改POST操作中的选定值。例如,您呈现了一个表单,用户在下拉列表中选择了一些值,提交了表单,并在POST操作中对此选定值进行了一些处理,当您重新显示视图时,您希望下拉列表中选择了其他值。在这种情况下,您将不得不删除ModelState中包含的初始选择,或者Html帮助器将忽略模型中的选定值:
// do this before returning the view and only if your scenario
// corresponds to what I described above
ModelState.Remove("ListId");
答案 3 :(得分:0)
这个问题的解决方案更简单,我们都认为......
我们需要做的就是在视图模型上为下拉列表绑定的元素设置属性 - 例如:ListId = 3,例如
当我们这样做时
Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {@class="someClass"})
HtmlHelper将自动获取要在DropDownList
上显示的默认值simples!
希望它可以帮助你和所有其他人 - 像我一样! - 为这个明显的问题寻找解决方案已经失去了很多时间。