【问题标题】:Writing a code trigger for the updatepanel. C# - ASP.NET为更新面板编写代码触发器。 C# - ASP.NET
【发布时间】:2011-05-29 15:26:51
【问题描述】:

我有这个要在我的网站中使用的 UpdatePanel。基本上,这个想法是用户单击一个链接并在服务器上启动一个服务,该服务将更改数据库。

所以我想写的是一个方法,如果数据库被更新,它将返回 true 或 false。该方法应按时间间隔运行。如果数据库已更新,它将返回 true,这将触发 UpdatePanel 进行更新。

我知道您可以通过控件添加触发器。但是也可以通过代码来实现吗?这个想法是,如果用户在开始操作后停留在页面上,他将在方法返回 true 时看到结果出现。如果用户离开页面,他当然什么也看不到。

如果这不是使用它的权利,请说出来。

任何评论将不胜感激! 亲切的问候, 弗洛里斯

【问题讨论】:

    标签: c# asp.net background updatepanel


    【解决方案1】:

    我建议你使用 asp:Timer

    您可以将此计时器放置在更新面板的内部或外部。如果将其放在更新面板中,则不必自己处理触发器。 upatepanel 中的每个帖子都将变为异步。但是如果你把它放在外面,你必须分配触发器。

    这里是您的 aspx 的示例代码:

         <asp:UpdatePanel runat="server" ID="UPanel1">
            <ContentTemplate>
                <asp:Label ID="MessageLabel" runat="server" ForeColor="Red" Font-Size="X-Large" />
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
            </Triggers>
        </asp:UpdatePanel>
        <asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Clicked" Interval="1000" /> 
    

    虽然将其放在更新面板中更容易:

    <asp:UpdatePanel runat="server" ID="UPanel1">
        <ContentTemplate>
            <asp:Label ID="MessageLabel" runat="server" ForeColor="Red" Font-Size="X-Large" />
             <asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Clicked" Interval="1000" />
        </ContentTemplate>
    </asp:UpdatePanel>
    

    现在在c#端,你必须像这样编写事件处理方法:

            private static int counter = 0;
            protected void Timer1_Clicked(object sender, EventArgs e)
            {
                //DO YOUR WORK WITH DATABASE HERE INSTEAD OF THIS CODE
    
                if (++counter < 5)
                    return;
    
                MessageLabel.Text = "Tadaaaaaah";
            }
    

    在本例中,5 秒后屏幕上会出现一个 tadaaaah。 您应该在此事件处理程序中更新您的面板。即设置标签的文本。 我希望我能解决你的问题。

    【讨论】:

    • 好吧,你的方法行得通,唯一烦人的是使屏幕闪烁的回发。
    • 通过仅在人们单击链接时启用计时器来修复它。这样会减少烦人的回发。
    【解决方案2】:

    您可以检查数据库中的值是否更新,然后如果更新,您应该将下面的代码放在 if 部分中

    如果(条件) {

    //Creates a new async trigger
        AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
    
        //Sets the control that will trigger a post-back on the UpdatePanel
        trigger.ControlID = "lnkbtncommit";
    
        //Sets the event name of the control
        trigger.EventName = "Click";
    
        //Adds the trigger to the UpdatePanels' triggers collection
        pnlUpdate.Triggers.Add(trigger);
    }
    

    【讨论】:

    • 这将设置触发器,但这不会以一系列间隔运行,对吧?我想要的是 UpdatePanel 在条件为真时更新,而不是在条件为真时设置触发器。
    猜你喜欢
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多