[ASP.NET AJAX]How to register javascript functions after UpdatePanel updated
As an ASP.NET fellow, UpdatePanel just like one artifacts. It can make all the contents in one UpdatePanel get an partial-refresh(AJAX) feature.
Usually, we need to call a javascript function after we update the content in the UpdatePanel. Without UpdatePanel, we could add onclick attribute to one button or use Page.ClientScript to register the script in code-behind. But in the UpdatePanel, Page.ClientScript will lose efficacy.
In this document, I want to discuss some methods to register javascript functions after the UpdatePanel updated.
ASP.NET Extension provide us some useful and direct ways to call a javascript function both in client-side and server-side.
Client-side:
Method A:
Look at this code snippet:
02 <asp:ScriptManager ID="ScriptManager1" runat="server">
03 </asp:ScriptManager>
04
05 <script type="text/javascript">
06 function pageLoad(sender, e) {
07 alert("Page is re-loaded!");
08 }
09 </script>
10
11 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
12 <ContentTemplate>
13 <%=DateTime.Now.ToString() %>
14 </ContentTemplate>
15 <Triggers>
16 <asp:AsyncPostBackTrigger ControlID="TriggerTimer" EventName="Tick" />
17 </Triggers>
18 </asp:UpdatePanel>
19
20 <asp:Timer ID="TriggerTimer" runat="server" Interval="5000">
21 </asp:Timer>
22 </form>
In this snippet, we could see we register the pageLoad function directly in the page. the function pageLoad will be executed when the page first load and each asynchronous postback which caused by UpdatePanel.
Method B:
The code above in pageLoad is same as the code below.
2 window.onload = function () {
3 Sys.Application.add_load(function () {
4 alert("Page re-loaded!");
5 });
6 }
7 </script>
Server Side:
For server side, we need to use a method, ScriptManager.RegisterClientScriptBlock, for more details about this method, please view this link in MSDN:http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerclientscriptblock.aspx. This method registers a client script block with the ScriptManager control for use with a control that is inside an UpdatePanel control, and then adds the script block to the page.
For example,
2 {
3 ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "RegScript",
4 "alert('Page re-loaded!');", true);
5 }
The result is same as the methods which talked above.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述