【问题标题】:ASP.NET DropDownList / HTML select list default selectionASP.NET DropDownList / HTML 选择列表默认选择
【发布时间】:2011-03-17 15:34:38
【问题描述】:

对于我的 ASP.NET 页面,在后面的代码中,我将各种项目/选项加载到 DropDownList 中,但我没有通过分配 SelectedIndex 来设置默认值。我注意到回发 SelectedIndex 设置为 0,即使我从未将焦点设置为或更改 DropDownList 中的值。

如果后面的代码或标记中没有另外指定,是否将默认值 0 用于带有 DropDownList 的回发中的 SelectedIndex?如果是,这是否是选择列表的 HTML 标准的一部分,或者这只是为 ASP.NET 实现的方式?

【问题讨论】:

    标签: asp.net html select drop-down-menu selectedindex


    【解决方案1】:

    对于从后面的代码中寻找方法的任何人,您可以使用Insert 函数并指定Index 为0 来添加额外的列表项,如SO Question 中所述。请确保在您致电DataBind()后这样做

    myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo Code
    myDropDownList.DataTextField = "Value";
    myDropDownList.DataValueField = "Id";
    myDropDownList.DataBind();
    
    myDropDownList.Items.Insert(0, new ListItem("Please select", ""));
    

    【讨论】:

      【解决方案2】:

      这是 HTML SELECT 控件的正常行为。

      除非使用 selected 属性,否则它将始终从第一项(索引为 0)开始。

      在许多情况下,我不希望在 ASP.NET 中这样做,因为我特别希望用户选择一个选项。

      所以我要做的是添加一个空白项,然后我可以对其进行验证。

      <asp:DropDownList runat="server" DataSourceID="SomeDS" AppendDataBoundItems="true"> // Notice the last property
          <asp:ListItem Text="Please select an option" Value="" />
      </asp:DropDownList>
      

      这样,我可以设置一个验证器来检查值是否为空,从而强制用户做出选择。

      【讨论】:

        猜你喜欢
        • 2013-09-17
        • 1970-01-01
        • 2019-06-05
        • 1970-01-01
        • 2016-02-20
        • 2013-10-19
        • 2016-03-25
        • 2017-12-08
        • 1970-01-01
        相关资源
        最近更新 更多