c# - 为什么我的 SelectList 填充了一个不需要的空白选项

标签 c# asp.net asp.net-mvc razor

我正在努力创建一个包含下拉列表的 View 。为了生成选择列表项,我编写了一个方法来返回 SelectListItem 的列表。此下拉列表所需 - 其中一个具有 Selected 属性设置为 true。

我已经追踪了生成 IEnumerable<SelectListItem> 的方法代表我希望呈现的选项,它正在返回所需的结果。

但是当我使用 Html.DropDownList() 时利用IEnumerable<SelectListItem>返回上面,我呈现的选择元素 有一个初始的空白选项,它不会出现在 DOM 中。选择任何选项都会将其删除,但我很困惑为什么 从 List<SelectListItem> 中选择的选项不被尊重。

SelectListItem的静态方法生成列表| :

public static IEnumerable<SelectListItem> GetDropDownValues()
{
    IEnumerable<MyClass> myClassesForList = MyClass.GetItemsForList();
    List<SelectListItem> retVal = new List<SelectListItem>();
    retVal.Add(new SelectListItem() { Text = "Choose", Value = "0", Selected=true });

    IEnumerable<SelectListItem> myClassesSelectListItems =
        from x in myClassesForList
        select new SelectListItem
        {
            Text = x.Name,
            Value = x.Value
        };

    return retVal.Concat(myClassesSelectListItems);
}

相关的 Razor 片段:

@Html.DropDownList("dropDownVals", GetDropDownValues())

编辑 1:结果下拉列表的屏幕截图

Screenshot of resulting DropDownList

最佳答案

确保没有名为 dropDownVals 的 viewbag/viewdata,它保存的值不存在于 GetDropDownValues 方法返回的列表中

如果您使用 AddRange 而不是 Concat 会怎样:

retVal.Add(new SelectListItem() { Text = "Choose", Value = "0", Selected=true });
var myClassesSelectListItems = from x in myClassesForList
                               select new SelectListItem
                               {
                                   Text = x.Name,
                                   Value = x.Value
                               };

retVal.AddRange(myClassesSelectListItems);

return retVal;

关于c# - 为什么我的 SelectList 填充了一个不需要的空白选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31306896/

相关文章:

c# - 在 C# 中将 PerspectiveCamera 移动到它所面对的方向

c# - 从泛型类获取 ICollection 类型属性的列表

c# - 如何生成动态for循环

ASP.NET 确定在页面加载事件中的 updatepanel 内单击了哪个按钮

c# - Windows 通用应用程序串行端口无法打开,SerialDevice.FromIdAsync 始终为空

javascript - jquery-3-3-1 中已弃用的 .live() 语句的正确替代是什么

c# - 在 SelectList 集合中设置选定项

javascript - 在 Canvas 中隐藏对象

c# - 如何配置 Visual Studio 2017 以在 ASP.Net MVC https 站点中公开非加密端口

c# - 使用javascript从html文本框中获取值