具有单选按钮列表选择的不连贯回发行为

问题描述 投票:0回答:1

我有一个:

  • RadioButtonList,默认情况下为第一项选择。

  • LinkBut​​ton取消选择此选项。

  • LinkBut​​ton以显示RadioButtonList的索引

如果单击取消选择,然后单击保存,则会显示第一项的索引0。这种看似错误的行为是由重新加载页面并根据默认设置进行选择的回发引起的。

但是:如果我现在选择列表的Item2,然后单击保存,则我期望与回发将RadioButtonList重置为其初始值的行为相同。但是显示列表项2的索引1。

因此,“未选择”在回发时被否决,而“已选择”则不被回传!真的是那样吗?令人困惑且难以处理。

    <asp:RadioButtonList ID="RBL_SelectType" runat="server">
        <asp:ListItem Text="Choice1" Value="0" Selected="True" />
        <asp:ListItem Text="Choice2" Value="1" />
    </asp:RadioButtonList>

    <asp:LinkButton ID="LB_Reset" runat="server" OnClick="Unselect">unselect RBL</asp:LinkButton>
    <asp:LinkButton ID="LB_Save" runat="server" OnClick="Save">Save</asp:LinkButton>

    <asp:Label runat="Server" ID="Message" />

with:

    protected void Save(object sender, EventArgs e)
    {
        Message.Text = "Index = " + Convert.ToString(RBL_SelectType.SelectedIndex);
    }

    protected void Unselect(object sender, EventArgs e)
    {
        RBL_RBL_SelectType.SelectedIndex = -1;
    }
c# asp.net postback radiobuttonlist
1个回答
0
投票

这是我所遇到问题的一种解决方案,尽管它不能解释我眼中一直不连贯的行为;我希望收到其他用户对此行为的更多反馈或确认。

因此,每当您需要为RadioButtonList设置默认选择时,都不要在标记中进行选择,因为它会在回发后使选择“未选择”失去选择,但要在page_load后面的代码中进行选择。

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
       RBL_SelectType.SelectedIndex = 0;
   }
© www.soinside.com 2019 - 2024. All rights reserved.