我可以使用 SelectedIndex 而不是 SelectedValue 来保存 DropDownList 的状态吗?
Can I save the state of a DropDownList using the SelectedIndex instead of the SelectedValue?
我有一个场景,我的 DropDownList 由最终用户动态填充。但是,有时,两个或多个项目可能具有相同的价值。例如:
<asp:DropDownList runat="server" ID="ddl" AutoPostBack="true">
<asp:ListItem Text="Item 1" Value="Item 1" />
<asp:ListItem Text="Item 2" Value="Item 2" />
<asp:ListItem Text="Item 3" Value="Item 2" />
</asp:DropDownList>
当我select第三项时,ASP.NETselect在页面刷新时是第二项,因为两者的值相同。因此,它不使用 selected 索引,而是使用 selected 值。有没有办法改变我的应用程序的这种行为?
我动态添加了所有控件,所以如果我能有一种优雅的方式自动为我添加到网页的每个控件执行此操作,那就太好了。有什么建议吗?
更新 1:
向 github 添加了示例项目:https://github.com/vmrocha/dropdown-issue
您可以为每个项目添加一个自定义属性,将实际值存储在其中并在代码隐藏中检索它。然后可以为所有项目(例如索引)将 Value
属性设置为不同的值:
<asp:DropDownList runat="server" ID="ddl" AutoPostBack="true">
<asp:ListItem Text="Item 1" Value="1" Tag="Value1" />
<asp:ListItem Text="Item 2" Value="2" Tag="Value2" />
<asp:ListItem Text="Item 3" Value="3" Tag="Value2"/>
</asp:DropDownList>
在代码隐藏中:
string actualSelectedValue = ddl.SelectedItem.Attributes["Tag"];
我有一个场景,我的 DropDownList 由最终用户动态填充。但是,有时,两个或多个项目可能具有相同的价值。例如:
<asp:DropDownList runat="server" ID="ddl" AutoPostBack="true">
<asp:ListItem Text="Item 1" Value="Item 1" />
<asp:ListItem Text="Item 2" Value="Item 2" />
<asp:ListItem Text="Item 3" Value="Item 2" />
</asp:DropDownList>
当我select第三项时,ASP.NETselect在页面刷新时是第二项,因为两者的值相同。因此,它不使用 selected 索引,而是使用 selected 值。有没有办法改变我的应用程序的这种行为?
我动态添加了所有控件,所以如果我能有一种优雅的方式自动为我添加到网页的每个控件执行此操作,那就太好了。有什么建议吗?
更新 1:
向 github 添加了示例项目:https://github.com/vmrocha/dropdown-issue
您可以为每个项目添加一个自定义属性,将实际值存储在其中并在代码隐藏中检索它。然后可以为所有项目(例如索引)将 Value
属性设置为不同的值:
<asp:DropDownList runat="server" ID="ddl" AutoPostBack="true">
<asp:ListItem Text="Item 1" Value="1" Tag="Value1" />
<asp:ListItem Text="Item 2" Value="2" Tag="Value2" />
<asp:ListItem Text="Item 3" Value="3" Tag="Value2"/>
</asp:DropDownList>
在代码隐藏中:
string actualSelectedValue = ddl.SelectedItem.Attributes["Tag"];