asp.net-mvc – ASP.NET MVC DropDownListFor不支持SelectListItem.Selected

我正在使用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.
>删除选项标签参数.
>删除HTML属性对象.
>在DropDownListFor中使用SelectList:

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的视图调用

解决方法

试试这样:
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,OptionLabel = "Click to Select"
});

并在视图中:

<%= Html.DropDownListFor(
    m => m.ListId,"Text"),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");

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...