Tuesday, January 5, 2010

Execute Javascript function after updating UpdatePanel

UpdatePanel is Control of Microsoft ASP.NET AJAX which allows to integrate conveniently enough AJAX into your application. In this article I wish to show as to execute client JavaScript on end of the next updating of this panel. We add EndRequestHandler in request manager:

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

Here the example of the web form with two TextBox where you enter the text, and a server returns length of the text and displays it in the second TextBox:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  
<title></title>

  
<script type="text/javascript">
 
function EndRequestHandler(sender, args) {
 
if (args.get_error() == undefined)
 alert(
"Your text has: " + document.getElementById("txtLength").value + " character(s)");
 
else
 alert(
"There was an error" + args.get_error().message);
 }
 
function load() {
 Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
 }
  
</script>

</head>
<body onload="load();">
  
<form id="form1" runat="server">
  
<asp:ScriptManager ID="_scriptManager" runat="server" />
  
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    
<ContentTemplate>
      Write something:
      
<asp:TextBox ID="txtData" runat="server" AutoPostBack="true" OnTextChanged="txtDataOnChange" />
      
<br />
      Server says the length is:
      
<asp:TextBox ID="txtLength" runat="server" AutoPostBack="true" />
    
</ContentTemplate>
  
</asp:UpdatePanel>
  
</form>
</body>
</html>

No comments:

Post a Comment