Monday, June 13, 2011

Client Callbacks in ASP.NET

Some time a situation comes wherein you want to process some server side processing without refreshing the whole page. This can be achived by using Microsoft ajax controls like "UpdatePanel" but some time you want to implement a functionality on your own in that case you can use your own client Callbacks.
For this first we will implement the System.Web.UI.ICallbackEventHandler. The ICallbackEventHandler has two methods.
1. GetCallbackResult : This method will return the reslut of server side processing.

2. RaiseCallbackEvent : This method will be called by client and you can use it to get the parameter values from client.

In this example I have used a Textbox and getting the value of that text box value in a lable while typing in textbox.


Code
    
   

Welcome to ASP.NET!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CallbackExample
{


    public partial class _Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
    {
        string _result = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            //callback reference of the client-side function which will be called after the completion of server side processing. 
            string callbackRef = Page.ClientScript.GetCallbackEventReference(this, "args", "ClientFunction", "");
            // Javascript function that will be called from client to call the server
            string callBackFunctionScript = @"function CallServerFunction(args){" + callbackRef + "}";
            // Now register the script on the page
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServerFunction", callBackFunctionScript, true);
        }

        public string GetCallbackResult()
        {
            //throw new NotImplementedException();
            return _result;


        }

        public void RaiseCallbackEvent(string eventArgument)
        {
            _result = eventArgument;
        }

        
    }
}







Download Code