简体   繁体   English

Radiobuttonlist 事件并不总是触发

[英]Radiobuttonlist event not always firing

I have a radiobuttonlist with a selectedindexchanged event that updates a search function.我有一个带有 selectedindexchanged 事件的 radiobuttonlist 更新搜索功能。 One of the items is specified in the aspx, and the others are appended databound items.其中一项在 aspx 中指定,其他项是附加的数据绑定项。 No matter what I set as the default, that item will not fire the event.无论我将什么设置为默认值,该项目都不会触发该事件。 All other items will fire the event.所有其他项目都将触发该事件。 Also, it seems that after the "dead" item is selected, the event won't fire at all.此外,似乎在选择“死”项目后,事件根本不会触发。

How can I track down the error and correct?我如何追踪错误并纠正? Here is current code.这是当前的代码。

EDIT: Sorry if the short version was misleading.编辑:抱歉,如果简短版本具有误导性。 I wasn't sure what to include.我不确定要包括什么。 Here is the whole page.这是整个页面。

All aspx:所有aspx:

     <%@ Page Language="C#" MasterPageFile="~/MSDS/MSDS.master" EnableEventValidation="false"
    AutoEventWireup="true" CodeFile="SearchMSDS.aspx.cs" Inherits="MSDS_ByDept" Title="NCLWeb - Search MSDS" %>

<%@ Register Assembly="SqlWhereBuilder" Namespace="UNLV.IAP.WebControls" TagPrefix="cc1" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PageContent" runat="Server">
    <h2>
        <asp:Label ID="lblTitle" runat="server">Search Active MSDS</asp:Label></h2>
    <table class="style1">
        <tr>
            <td style="width: 435px" valign="top">
                <asp:Panel runat="server" ID="pnlSearch" DefaultButton="btnSearch">
                    <asp:TextBox ID="txtSimpleSearch" runat="server" Width="262px"></asp:TextBox>
                    <asp:Button ID="btnSearch" runat="server" Text="Search" Width="96px" OnClick="btnSearch_Click" />
                    <br />
                    <asp:LinkButton ID="btnAdvSearch" runat="server" OnClick="btnAdvSearch_Click" Font-Size="Small">Show Advanced Search</asp:LinkButton>
                </asp:Panel>
                <asp:Panel ID="pnlAdvSearch" runat="server" Width="635px" DefaultButton="btnRunAdvSearch">
                    <asp:Button ID="btnRunAdvSearch" runat="server" OnClick="btnRunAdvSearch_Click" Text="Advanced Search" />
                    <cc1:SqlWhereBuilder ID="SqlWhereBuilder1" runat="server" ClientCodeLocation="../JavaScripts/SqlWhereBuilder.js"
                        FieldsFile="../ConfigFiles/SearchMSDS.config" OperatorListsFile="../ConfigFiles/SearchMSDS.config"
                        ValueEntryFile="../ConfigFiles/SearchMSDS.config">
                    </cc1:SqlWhereBuilder>
                    <br />
                    <br />
                </asp:Panel>
                <cc2:CollapsiblePanelExtender ID="pnlAdvSearch_CollapsiblePanelExtender" runat="server"
                    CollapseControlID="btnAdvSearch" Collapsed="True" Enabled="True" ExpandControlID="btnAdvSearch"
                    TargetControlID="pnlAdvSearch">
                </cc2:CollapsiblePanelExtender>
            </td>
            <td valign="top">
                <asp:Panel ID="pnlStatus" runat="server">
                    <asp:RadioButtonList ID="rblStatus" runat="server" AppendDataBoundItems="True"
                        AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="DisplayValue"
                        DataValueField="Value" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
                        RepeatDirection="Horizontal" CellPadding="3" CellSpacing="3" 
                        CausesValidation="True" Visible="True">
                        <asp:ListItem Selected="True">All</asp:ListItem>
                    </asp:RadioButtonList>
                </asp:Panel>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
                    SelectCommand="getOptionList" SelectCommandType="StoredProcedure">
                    <SelectParameters>
                        <asp:Parameter DefaultValue="msds_Status" Name="ListName" Type="String" />
                    </SelectParameters>
                </asp:SqlDataSource>
                <asp:UpdatePanel runat="server" ID="upd2">
                    <ContentTemplate>
                        <asp:Button ID="btnExport" runat="server" Text="Export Results" 
                            OnClick="btnExport_Click1" UseSubmitBehavior="False" />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </td>
        </tr>
    </table>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="100" DynamicLayout="False">
                <ProgressTemplate>
                    <img src="../images/loading.gif" alt="Loading..." style="text-align: center" />
                    <asp:Label ID="lblProgress" runat="server"></asp:Label></ProgressTemplate>
            </asp:UpdateProgress>
            <asp:GridView ID="gridResults" runat="server" DataSourceID="sqlMSDS" OnRowDataBound="GridView1_RowDataBound"
                AllowPaging="True" PageSize="25" AllowSorting="True" OnSelectedIndexChanged="gridResults_SelectedIndexChanged"
                AutoGenerateColumns="False" EmptyDataText="No matching MSDS Sheets." OnSorted="gridResults_Sorted">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" Visible="false"
                        ReadOnly="True" SortExpression="ID" />
                    <asp:BoundField DataField="ChemicalTitle" HeaderText="ChemicalTitle" SortExpression="ChemicalTitle" />
                    <asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" />
                    <asp:BoundField DataField="UsageDept" HeaderText="UsageDept" SortExpression="UsageDept" />
                    <asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
                    <asp:BoundField DataField="Health" HeaderText="Health" visible="false" SortExpression="Health" />
                    <asp:BoundField DataField="Fire" HeaderText="Fire"  visible="false" SortExpression="Fire" />
                    <asp:BoundField DataField="Reactivity" HeaderText="Reactivity"  visible="false" SortExpression="Reactivity" />
                    <asp:BoundField DataField="DateUpdated" HeaderText="DateUpdated" SortExpression="DateUpdated" />
                </Columns>
                <SelectedRowStyle BackColor="Yellow" />
            </asp:GridView>
            <asp:SqlDataSource ID="sqlMSDS" OnSelected="sqlMSDS_OnSelected" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
                SelectCommand="SELECT [ID]
                                      ,[ChemicalTitle]
                                      ,[Manufacturer]
                                      ,[UsageDept]
                                      ,[Notes]
                                      ,[Health]
                                      ,[Fire]
                                      ,[Reactivity]
                                      ,[DateUpdated]
                                      FROM [msds_Sheets]" OnSelecting="sqlMSDS_Selecting"></asp:SqlDataSource>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnSearch" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="btnRunAdvSearch" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="rblStatus" EventName="SelectedIndexChanged" />
            <asp:AsyncPostBackTrigger ControlID="btnExport" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>
    <br />
</asp:Content>

And code-behind:和代码隐藏:

    List<String> safeWords = new List<String>();

protected void Page_Load(object sender, EventArgs e)
{
    pnlStatus.Visible = User.IsInRole("msds_Admin");

    gridResults.DataKeyNames = new String[] { "id" };

    txtSimpleSearch.Focus();

    if (!IsPostBack)
    {
        safeWords.Add("delete");
        safeWords.Add("insert");
        safeWords.Add("update");
        safeWords.Add("set");
        safeWords.Add("exec");
        safeWords.Add("N'");

        sqlMSDS.SelectCommand += " Where status = 0 ";

        Session["Sql"] = sqlMSDS.SelectCommand;

        try
        {
            Session["OriginalSQL"] = sqlMSDS.SelectCommand.Remove(sqlMSDS.SelectCommand.IndexOf("Where"));
        }
        catch (Exception)
        {
            Session["OriginalSQL"] = sqlMSDS.SelectCommand;
        }
    }
}

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ((Label)UpdateProgress1.FindControl("lblProgress")).Text = "Searching...";

            if (btnSearch.Visible)
            {
                btnSearch_Click(null, null);

                if (RadioButtonList1.SelectedValue != "All")
                {
                    sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
                }
                else
                {
                    //Somehow force the grid to research using no status parameter
                    sqlMSDS.SelectCommand = Session["Sql"].ToString();
                }
            }
            else
            {
                btnRunAdvSearch_Click(null, null);

                if (RadioButtonList1.SelectedValue != "All")
                {
                    if (sqlMSDS.SelectCommand.Contains("Where"))
                    {
                        sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
                    }
                    else
                    {
                        sqlMSDS.SelectCommand += " Where Status = " + RadioButtonList1.SelectedValue;
                    }
                }
                else
                {
                    //Somehow force the grid to research using no status parameter
                    sqlMSDS.SelectCommand = Session["Sql"].ToString();
                }
            }
        }

Here is what was happening to me and the fix.这是发生在我身上的事情和修复。

I had a radiobuttonlist that was not in an update panel, but defined as a trigger for an update panel.我有一个不在更新面板中的单选按钮列表,但被定义为更新面板的触发器。 I had onselectedindexchanged defined as well.我也定义了 onselectedindexchanged 。 Radiobuttonlist had the first listitem attribute selected="true", so it would be selected by default on page load. Radiobuttonlist 的第一个 listitem 属性 selected="true",因此默认情况下会在页面加载时选择它。 Then selecting the second listitem worked fine, posting back and updating the update panel.然后选择第二个列表项工作正常,回发并更新更新面板。

However, selecting the first item again was not firing onselectedindexchanged event.但是,再次选择第一项不会触发 onselectedindexchanged 事件。 Using Firefox's awesome Inspect Element utility, I was able to determine that the server was generating the html element (checked only on the first, default list item).使用 Firefox 很棒的 Inspect Element 实用程序,我能够确定服务器正在生成 html 元素(仅在第一个默认列表项上进行检查)。 But since the radiobuttonlist was not in the update panel, the checked="checked" attribute for the second item was never getting written to the browser, even though client-side the second radio button visually appeared to be selected.但是由于radiobuttonlist 不在更新面板中,第二个项目的checked="checked" 属性从未被写入浏览器,即使客户端第二个单选按钮在视觉上看起来被选中。 Therefore, when selecting the original item the second time, the onselectedindexchanged was not firing server-side, because the newly selected index was already indicated as selected in the POST event.因此,当第二次选择原始项目时,onselectedindexchanged 不会触发服务器端,因为新选择的索引已经在 POST 事件中指示为已选择。

You won't see this problem if the list is inside the panel you want to refresh, because the postback causes the browser to receive "new" elements with the checked="checked" on the newly selected item.如果列表在您要刷新的面板内,您将不会看到此问题,因为回发会导致浏览器在新选择的项目上接收带有 checked="checked" 的“新”元素。 The layout of my page made it inconvenient to have these in the same panel, so the fix for me was to put the radiobuttonlist in it's own little update panel.我的页面布局使得将它们放在同一个面板中很不方便,所以我的解决方法是将 radiobuttonlist 放在它自己的小更新面板中。 Whichever works for you, the answer is to make sure the radiobuttonlist is in SOME update panel, so the checked attribute can be sent to the browser for each item when selected.无论哪种方式适合您,答案是确保单选按钮列表位于某些更新面板中,以便选中时可以将每个项目的选中属性发送到浏览器。

Does this RadioButtonList specified as AsyncPostBackTrigger for another UpdatePanel?此 RadioButtonList 是否指定为另一个 UpdatePanel 的 AsyncPostBackTrigger? If so, check following link: CheckedChanged event not firing on a radio button within UpdatePanel如果是这样,请检查以下链接: CheckedChanged 事件未在 UpdatePanel 中的单选按钮上触发

I have reproduce that behaviour and fix this with the following script:我已重现该行为并使用以下脚本修复此问题:

 $(function () {
        $("input[type='radio']:first", $("#<%= RadioButtonList1.ClientID %>")).attr("checked", true);
    });

if you can't use the jQuery try this javascript:如果你不能使用 jQuery 试试这个 javascript:

 window.onload = function () {
        window.document.getElementById("<%= RadioButtonList1.ClientID %>_0").checked = true;
    };


protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "RadioButtonListDefaultValue", String.Format("window.document.getElementById('{0}_0').checked = true;", RadioButtonList1.ClientID), true);
        }
    }

As user user2965308 said, if the RadioButtonList is inside of the UpdatePanel this issue doesn't happen.正如用户 user2965308 所说,如果 RadioButtonList 在 UpdatePanel 内,则不会发生此问题。

https://www.codeproject.com/Questions/118042/RadioButtonList-Postback-issue-when-selected-by-co "Get it inside an update panel, with property "ChildrenAsTriggers" on true. This solve the issue for me." https://www.codeproject.com/Questions/118042/RadioButtonList-Postback-issue-when-selected-by-co “在更新面板中获取它,属性“ChildrenAsTriggers”为真。这为我解决了这个问题。 ”

<asp:ListItem Selected="True">All</asp:ListItem>

Clicking "All" doesn't change the selected index since that item was already selected, so the event does not fire.单击“全部”不会更改所选索引,因为该项目已被选中,因此不会触发该事件。 Picking any other option changes the selected option and causes the event to fire.选择任何其他选项会更改所选选项并导致事件触发。 I believe your goal is to display results for all statuses when you click on "All".我相信您的目标是在单击“全部”时显示所有状态的结果。 You should do one of the following:您应该执行以下操作之一:

  • Display those results when the page initially loads since "All" is already selected.由于已选择“全部”,因此在页面最初加载时显示这些结果。
  • Add a "Search" button that initiates the post-back instead of using the radio button's AutoPostBack.添加启动回发的“搜索”按钮,而不是使用单选按钮的 AutoPostBack。
  • Replace the RadioButtonList with a DropDownList, and give it two initial ListItems: "Pick a Status" - whose value is an empty string, and "All" whose value is "All".将 RadioButtonList 替换为 DropDownList,并为其提供两个初始 ListItem:“Pick a Status” - 其值为空字符串,以及“All”,其值为“All”。 The "Pick a Status" dummy entry would look less out of place in a DropDownList than in a RadioButtonList. “选择状态”虚拟条目在 DropDownList 中看起来不像在 RadioButtonList 中那么不合适。

Of the options listed above, I would personally prefer the "Search" button, because AutoPostBack annoys me as a user.在上面列出的选项中,我个人更喜欢“搜索”按钮,因为 AutoPostBack 使我作为用户感到恼火。 I hate AutoPostBack DropDownLists that make the web page go bonkers when I accidentally use my mouse wheel when the list has focus.我讨厌 AutoPostBack DropDownLists,当我在列表有焦点时不小心使用鼠标滚轮时,它会使网页变得疯狂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM