ClientScriptManager.GetCallbackEventReference Method (Control, String, String, String)

 

Obtains a reference to a client function that, when invoked, initiates a client call back to a server event. The client function for this overloaded method includes a specified control, argument, client script, and context.

Namespace:   System.Web.UI
Assembly:  System.Web (in System.Web.dll)

Public Function GetCallbackEventReference (
	control As Control,
	argument As String,
	clientCallback As String,
	context As String
) As String

Parameters

control
Type: System.Web.UI.Control

The server Control that handles the client callback. The control must implement the ICallbackEventHandler interface and provide a RaiseCallbackEvent method.

argument
Type: System.String

An argument passed from the client script to the server

RaiseCallbackEvent method.

clientCallback
Type: System.String

The name of the client event handler that receives the result of the successful server event.

context
Type: System.String

The client script that is evaluated on the client prior to initiating the callback. The result of the script is passed back to the client event handler.

Return Value

Type: System.String

The name of a client function that invokes the client callback.

Exception Condition
ArgumentNullException

The Control specified is null.

InvalidOperationException

The Control specified does not implement the ICallbackEventHandler interface.

The GetCallbackEventReference(Control, String, String, String) method performs an out-of-band callback to the server that is a modified version of a page's normal life cycle. For more information, see Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages.

System_CAPS_noteNote

When the browser is Microsoft Internet Explorer (version 5.0 or later), the script callback mechanism is implemented through the Microsoft.XmlHttp COM object and requires the browser to be set to run ActiveX controls. For other browsers, an XMLHttpRequest using the browser's local Document Object Model (DOM) is used. To check whether a browser supports client callbacks, use the SupportsCallback property. To check whether a browser supports XML over HTTP, use the SupportsXmlHttp property. Both properties are accessible through the Browser property of the intrinsic ASP.NET Request object.

The GetCallbackEventReference overload of the GetCallbackEventReference method performs a callback synchronously using XML over HTTP. When sending data synchronously in a callback scenario, synchronous callbacks return immediately and do not block the browser. No two synchronous callbacks callback can execute at the same time in the browser. If a second synchronous callback is fired while one is currently pending, the second synchronous callback cancels the first and only the second callback will return.

To send data asynchronously, use one of the overloads that takes the useAsync parameter, which is a Boolean value controlling this behavior. In the asynchronous scenario you can have multiple pending callbacks; however, the order in which they return is not guaranteed to match the order in which they were initiated.

Additionally, this overload of the GetCallbackEventReference method specifies no client function to handle the case of an error condition generated by the RaiseCallbackEvent method. To specify a client error callback handler, use one of the overloads that takes the clientErrorCallback parameter.

The GetCallbackEventReference(Control, String, String, String) method takes an optional string argument parameter and returns a string. To pass in or to receive multiple values, concatenate values in the input or return string, respectively.

System_CAPS_noteNote

Avoid using the view state in the implementation of page or control properties that need be updated during script callback operations. If the properties are to survive page requests, you can use session state.

The following code example demonstrates how to use two overloads of the GetCallbackEventReference method in a client callback scenario that increments integers.

Two callback mechanisms are shown; the difference between them is the use of the context parameter. A ReceiveServerData1 client callback function is provided using the context parameter. In contrast, the ReceiveServerData2 client callback function is defined in a <script> block on the page. A RaiseCallbackEvent method is the server handler that increments the value that is passed to it and the GetCallbackResult method returns the incremented value as a string. If the RaiseCallbackEvent method returns an error, then the ProcessCallBackError client function is called.

<%@ Page Language="VB" %>
<%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Public cbCount As Integer = 0

    ' Define method that processes the callbacks on server.
    Public Sub RaiseCallbackEvent(ByVal eventArgument As String) _
    Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent

        cbCount = Convert.ToInt32(eventArgument) + 1

    End Sub

    ' Define method that returns callback result.
    Public Function GetCallbackResult() _
    As String Implements _
    System.Web.UI.ICallbackEventHandler.GetCallbackResult

        Return cbCount.ToString()

    End Function



    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        ' Define a StringBuilder to hold messages to output.
        Dim sb As New StringBuilder()

        ' Check if this is a postback.
        sb.Append("No page postbacks have occurred.")
        If (Page.IsPostBack) Then

            sb.Append("A page postback has occurred.")

        End If

        ' Write out any messages.
        MyLabel.Text = sb.ToString()

        ' Get a ClientScriptManager reference from the Page class.
        Dim cs As ClientScriptManager = Page.ClientScript

        ' Define one of the callback script's context.
        ' The callback script will be defined in a script block on the page.
        Dim context1 As New StringBuilder()
        context1.Append("function ReceiveServerData1(arg, context)")
        context1.Append("{")
        context1.Append("Message1.innerText =  arg;")
        context1.Append("value1 = arg;")
        context1.Append("}")

        ' Define callback references.
        Dim cbReference1 As String = cs.GetCallbackEventReference(Me, "arg", _
            "ReceiveServerData1", context1.ToString())
        Dim cbReference2 As String = cs.GetCallbackEventReference("'" & _
            Page.UniqueID & "'", "arg", "ReceiveServerData2", "", "ProcessCallBackError", False)
        Dim callbackScript1 As String = "function CallTheServer1(arg, context) {" + _
            cbReference1 + "; }"
        Dim callbackScript2 As String = "function CallTheServer2(arg, context) {" + _
            cbReference2 + "; }"

        ' Register script blocks will perform call to the server.
        cs.RegisterClientScriptBlock(Me.GetType(), "CallTheServer1", _
            callbackScript1, True)
        cs.RegisterClientScriptBlock(Me.GetType(), "CallTheServer2", _
            callbackScript2, True)

    End Sub
</script>

<script type="text/javascript">
var value1 = 0;
var value2 = 0;
function ReceiveServerData2(arg, context)
{
    Message2.innerText = arg;
    value2 = arg;
}
function ProcessCallBackError(arg, context)
{
    Message2.innerText = 'An error has occurred.';
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>ClientScriptManager Example</title>
</head>
<body>
    <form id="Form1" 
          runat="server">
    <div>
      Callback 1 result: <span id="Message1">0</span>
      <br />
      Callback 2 result: <span id="Message2">0</span>
      <br /> <br />
      <input type="button" 
             value="ClientCallBack1" 
             onclick="CallTheServer1(value1, alert('Increment value'))"/>    
      <input type="button" 
             value="ClientCallBack2" 
             onclick="CallTheServer2(value2, alert('Increment value'))"/>
      <br /> <br />
      <asp:Label id="MyLabel" 
                 runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

.NET Framework
Available since 2.0
Return to top
Show: