Implement ICallbackEventHandler Example

In this article, I have tried to explain an alternate way of achieving the AJAX functionality using ICallBackEventHandler. Many of the times we must have used core AJAX to partially update the page content. Using UpdatePanel can be another approach to partially update the page content. Here is a very simple example to populate a dropdown list using ICallbackEventHandler.

The page needs to implement ICallbackEventHandler interface and implement its methods.

  • public string GetCallbackResult()
  • public void RaiseCallbackEvent(string eventArgument)

In the following example I have used [Northwind] database and Microsoft EnterPrise Library for database Connectivity.You can use alternate ways to connect to Database if you are not having knowledge of Microsoft EnterPrise Library.

The page contains two dropdown List, ddlCategory and ddlSubcategory. ddlCategory gets populated on Page_load and ddlSubcategory populates on index change event of the ddlCategory Dropdown.

Just have a look into the below example to learn how you can implement AJAX functionality using ICallbackEventHandler.

Default.aspx Page

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<head runat=”server”>
<title>Implement ICallbackEventHandler</title>

<script language=”javascript” type=”text/javascript”>

function getSubCat(obj)
{
CallServer(obj.options[obj.selectedIndex].value, “”);
}

function ReceiveServerData(retValue)
{
var i=0;
var j=0;
var theDropDown=document.getElementById(“ddlSubcategory”);
var numberOfOptions = theDropDown.options.length ;
for (i=0; i<numberOfOptions; i++)
{
//Note: Always remove(0) and NOT remove(i)
theDropDown.remove(0);
}

var mydata=retValue.split(‘,’);
for(i=0;i<(mydata.length)/2;i++)
{
AddItem(mydata[j+1],mydata[j]);
j+=2;
}
}

function AddItem(Text,Value)
{
// Create an Option object
var opt = document.createElement(“option”);
// Add an Option object to Drop Down/List Box
document.getElementById(“ddlSubcategory”).options.add(opt);
// Assign text and value to Option object
opt.text = Text;
opt.value = Value;
}

</script>

</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<SPAN>Category</Span>
<asp:DropDownList ID=”ddlCategory” runat=”server” onchange=”getSubCat(this);”>
</asp:DropDownList>
<br />
<SPAN>Sub Category</Span>
<asp:DropDownList ID=”ddlSubcategory” runat=”server”>
</asp:DropDownList>
</div>
</form>
</body>
</html>

Default.aspx.cs Page

using System;
using System.Data;
using System.Web.Security;
using System.Web.UI;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Text;

public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
    string returnValue = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    { 
     if (!IsPostBack)
     {
      String cbReference = string.Empty;
      String callbackScript=string.Empty;
      cbReference =Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
      callbackScript = "function CallServer(arg, context)" + "{" + cbReference + ";}";
      Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
      BindCategory();
     }
    }

    private void BindCategory()
    {
        Database objDb = DatabaseFactory.CreateDatabase();
        IDataReader reader = null;

        try
        {            
            reader = objDb.ExecuteReader(CommandType.Text, 
                     "select RegionID,RegionDescription from region");
            ddlCategory.DataSource = reader;
            ddlCategory.DataValueField = reader.GetName(0).ToString();
            ddlCategory.DataTextField = reader.GetName(1).ToString();
            ddlCategory.DataBind();
        }
        catch(Exception ex)
        {

        }
        finally
        {
            if (reader != null)
                reader.Close();
        }
    }

    #region ICallbackEventHandler Members

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

    public void RaiseCallbackEvent(string eventArgument)
    {
        Database objDb = DatabaseFactory.CreateDatabase();
        IDataReader reader = null;
        StringBuilder sb = new StringBuilder();

        try
        {
            reader = objDb.ExecuteReader(CommandType.Text,
                    "select territoryID, territoryDescription from 
                    Territories where RegionID=" + eventArgument);
            
            while (reader.Read())
            {
                sb.Append(reader.GetString(0));
                sb.Append(",");
                sb.Append(reader.GetString(1));
                sb.Append(",");
            }
            sb.Remove(sb.Length - 1, 1);
            returnValue = sb.ToString();
        }
        catch (Exception)
        {
        }
        finally
        {
            if (reader != null)
                reader.Close();
        }
       // throw new NotImplementedException();
    }
    #endregion
}
Advertisements

About Gokul Dahal, Nepal

Software Engineer, Freelancer, Design and Develop web applications,Software Developer Nepal, FreeLancer Nepal Contact : gokuldahal@gmail.com
This entry was posted in ASP.NET, C# and tagged , , , , . Bookmark the permalink.

One Response to Implement ICallbackEventHandler Example

  1. Holly says:

    Great article, just what I was looking for.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s