简体   繁体   English

C#ASP.NET CheckBox_OnCheckedChanged未按预期触发

[英]C# ASP.NET CheckBox_OnCheckedChanged not firing as expected

I have an issue with both Checkbox_OnCheckedChanged and Dropdownlist_OnSelectedIndexChanged events not triggering the relevant functions in my code behind. 我对Checkbox_OnCheckedChangedDropdownlist_OnSelectedIndexChanged事件都没有问题,但没有触发我后面的代码中的相关功能。

Both Controls are bound to values in a GridView . 这两个控件都绑定到GridView值。 On the first OnCheckedChanged or OnSelectedIndexChanged event raised from the UI the functions in the code behind fire without error, however if I refresh my UpdatePanel , for example by changing the date range of the data inside the GridView and therefore loading more or less records, the OnCheckedChanged and OnSelectedIndexChanged functions are no longer called, however a PostBack occurs. 在从UI引发的第一个OnCheckedChangedOnSelectedIndexChanged事件上,后台代码中的函数正常运行,没有错误,但是,如果我刷新UpdatePanel ,例如通过更改GridView内数据的日期范围并因此加载或多或少的记录,不再调用OnCheckedChangedOnSelectedIndexChanged函数,但是发生PostBack发。

I believe that the functions are not being called as the function that rebinds the GridView is called instead: 我相信这些函数不会像重新绑定GridView的函数那样被调用:

 private void report_DateChanged(object sender, EventArgs e)
 {
        // Bind GridView here..
 }

however I cannot figure out why this happens. 但是我不知道为什么会这样。

I have a MasterPage: 我有一个MasterPage:

namespace ReportingSystemV2.Reporting
{
public partial class Reporting : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Attach to DateChanged Event on DateChange UserControl to Function
        DateRangeSelect.dateChanged += new DateRangeSelect.dateChangedEventHandler(dtRgSel_dateChanged);
    }

    // Declare an event for the content pages
    public event EventHandler reportDateChanged;

    // Called on a date change event
    protected void dtRgSel_dateChanged(object sender, DateChangedEventArgs e)
    {
        // Raise the event for content pages
        if (reportDateChanged != null)
            reportDateChanged(this, EventArgs.Empty);
    }
}

This MasterPage has a Control for selecting my date range.. MasterPage具有用于选择我的日期范围的Control

The main section of code for my control ascx code is: 我的控件ascx代码的代码主要部分是:

<%--UpdatePanel to trigger datechange--%>
<asp:UpdatePanel runat="server" ID="UpdatePanelDateChanged" OnLoad="UpdatePanelDateChanged_Load" >
</asp:UpdatePanel>

<%--When the date changes in javascript a postback is called in the updatepanel--%>
__doPostBack('<%=UpdatePanelDateChanged.ClientID %>', null);

And the the main section of code behind for this control is: 并且此控件后面的代码的主要部分是:

// Declare a delegate
public delegate void dateChangedEventHandler(object sender, DateChangedEventArgs e);

// Declare an event for any pages that have the control
public event dateChangedEventHandler dateChanged;

protected virtual void OnDateChanged(DateChangedEventArgs e)
{
    dateChangedEventHandler handler = dateChanged;

    // Raise the event
    if (handler != null)
        handler(this, e);
}

protected void UpdatePanelDateChanged_Load(object sender, EventArgs e)
{
   // Trigger the controls public event
   OnDateChanged(new DateChangedEventArgs(DateTime.Parse(dates[0]), DateTime.Parse(dates[1])));

}

In my content page my aspx code is: 在我的内容页面中, aspx代码为:

<%@ Page Title="Downtime" Language="C#" MasterPageFile="~/Reporting/Reporting.Master" AutoEventWireup="true" CodeBehind="GensetDowntime.aspx.cs" Inherits="ReportingSystemV2.Reporting.GensetDowntime" %>

<%@ MasterType VirtualPath="~/Reporting/Reporting.Master" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ReportingSubContent" runat="server">
<div class="container-fluid">
    <asp:UpdatePanel ID="updPanelDowntime" runat="server">
        <ContentTemplate>
            <div class="row">
                <div id="downtimeDiv" runat="server">
                    <asp:GridView ID="gridDowntime" runat="server" AutoGenerateColumns="False" GridLines="None" CssClass="table table-striped table-condensed"
                        OnRowDataBound="gridDowntime_RowDataBound"
                        OnSelectedIndexChanged="gridDowntime_SelectedIndexChanged"
                        DataKeyNames="ID,ID_Location,iddown,idup,dtdown,dtup,isexempt" EmptyDataText="No exempts in the selected period.">
                        <Columns>
                            <asp:TemplateField>
                                <ItemTemplate>
                            <asp:TemplateField HeaderText="Exempt?">
                                <ItemTemplate>
                                    <asp:DropDownList ID="ddlDowntimeExempt" AutoPostBack="true" runat="server"
                                        OnSelectedIndexChanged="ddlDowntimeExempt_SelectedIndexChanged">
                                        <asp:ListItem Value="-1">Unverified</asp:ListItem>
                                        <asp:ListItem Value="1">Yes</asp:ListItem>
                                        <asp:ListItem Value="0">No</asp:ListItem>
                                    </asp:DropDownList>
                                    <asp:Label ID="lblDowntimeExempt" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"isexempt")%>' Visible="false"></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Exclude?">
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkDowntimeExclude" runat="server" Checked='<%#Convert.ToBoolean(Eval("ISEXCLUDED")) %>' OnCheckedChanged="chkDowntimeExclude_CheckedChanged" AutoPostBack="true"/>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:CommandField ShowSelectButton="True" SelectText="Details" />
                        </Columns>

                    </asp:GridView>
                </div>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
</div>
</asp:Content>

And finally my code behind for my content page is: 最后,我的内容页面背后的代码是:

    protected void Page_PreInit(object sender, EventArgs e)
    {
        // Attach to UserControl Event on the MasterPage
        Master.reportDateChanged += new EventHandler(report_DateChanged);
    }

    // If the user changes the date lets update the table
    private void report_DateChanged(object sender, EventArgs e)
    {
        // Bind the gridview
    }

    // Function to be called when the ddl selectedindex is changed, only called on initial page load
    protected void ddlDowntimeExempt_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Applies the values selected in the exempt DDL to the database value
    }

    // function to be called when the checkbox checked state is change, again only called on the initial page loading - not after a postback
    protected void chkDowntimeExclude_CheckedChanged(object sender, EventArgs e)
    {
        // When the Exclude checkbox is changed, update the Db
    }

The code above shows the control that uses javascript to trigger a PostBack on an UpdatePanel , which triggers a public event in the Control . 上面的代码示出了control使用JavaScript来trigger一个PostBackUpdatePanel ,其triggers在一个公共事件Control The MasterPage has a function which is attached to the Control Event, this MasterPage functions updates a few values and triggers a new Event which is accessable to my ContentPage . MasterPage具有一个附加到Control Event的函数,该MasterPage函数更新一些值并触发一个新的Event,该事件可以访问我的ContentPage The ContentPage attaches a function to this MasterPage Event and when the DateRange is changed it will load the data for the GridView and bind it. ContentPage将一个函数附加到此MasterPage事件,并且当DateRange更改时,它将为GridView加载数据并将其绑定。

Master pages append extra names at the beginning of controls in "child" pages. 母版页在“子”页中控件的开头附加了多余的名称。 Most likely you are expecting the dropdown to have a name but it will have a different longer one like ctrl1$something$dropdown. 您最有可能期望下拉列表具有名称,但是它将具有不同的更长名称,例如ctrl1 $ something $ dropdown。

Check the ida using inspect in Chrome or dev tools to confirm that this is your problem first. 使用Chrome中的inspect或开发工具检查ida,以首先确认这是您的问题。

I think you're missing async postback triggers. 我认为您缺少异步回发触发器。 When an update panel partially posts back, it sends back the whole page, does the processing, and then returns only the portion that changed. 当更新面板部分回发时,它将发回整个页面,进行处理,然后仅返回更改的部分。 Probably in that process, slight ID changes have taken place and then there are missed registrations. 大概是在此过程中,ID发生了微小的变化,然后丢失了注册。 The report_DateChanged is fired most probably because it is the first control on the page that implements IPostBackEventHandler (because the postback on the checkbox and dropdown don't work any more) 触发report_DateChanged最大,因为它是实现IPostBackEventHandler的页面上的第一个控件(因为复选框和下拉菜单上的回发不再起作用)

To resolve that, explicitly add each control that should do an async postback to the update panel's triggers. 若要解决此问题,请明确将应进行异步回发的每个控件添加到更新面板的触发器。 like this: 像这样:

protected void gridDowntime_RowDataBound(object sender, GridViewRowEventArgs e)  
{  
    DropDownList ddl = e.Row.FindControl("ddlDowntimeExempt") as DropDownList;  
    CheckBox cb = e.Row.FindControl("chkDowntimeExclude") as CheckBox;  
    ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(ddl);  
    ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(cb);  
}  

Problem solved, by modifying the code in my DateRangeControl the UpdatePanel is no longer being triggered on all PostBacks , only those where it is called by __doPostBack('<%=UpdatePanelDateChanged.ClientID %>', null); 通过修改我的DateRangeControl的代码解决了问题,不再在所有PostBacks上触发UpdatePanel ,仅在那些由__doPostBack('<%=UpdatePanelDateChanged.ClientID %>', null);调用的位置上触发__doPostBack('<%=UpdatePanelDateChanged.ClientID %>', null); in my Javascript . 在我的Javascript

protected void UpdatePanelDateChanged_Load(object sender, EventArgs e)
{
    if (Request["__EVENTTARGET"] == UpdatePanelDateChanged.ClientID)
    {

        //Trigger Event
        OnDateChanged(new DateChangedEventArgs(DateTime.Parse(dates[0]), DateTime.Parse(dates[1])));

    }
}

Solution reference: http://encosia.com/are-you-making-these-3-common-aspnet-ajax-mistakes/ 解决方案参考: http://encosia.com/are-you-making-these-3-common-aspnet-ajax-mistakes/ : http://encosia.com/are-you-making-these-3-common-aspnet-ajax-mistakes/

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

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