Click here to Skip to main content
15,867,594 members
Articles / Web Development / XHTML
Article

ClientCallback custom control for web applications

Rate me:
Please Sign up or sign in to vote.
4.91/5 (51 votes)
19 Dec 2008CPOL3 min read 98.6K   1K   103   31
A client callback custom control and how to use it in WebForms.

TestPageImage2.JPG

Introduction

There are scenarios where we have a list of items on one side of a page (the list can be ordered or hierarchical) and on selection of an item from this list, all the details related to it is shown on the other half of the page. All this without a postback or a flicker would give a smooth and good feel to the user.

For example, we have a finance related Web application. We need to see the details related to a stock script in our portfolio (a number of scripts are listed on the same page). The moment a script is selected, all the details and the current status of the script is shown on the same page without any postback or flicker.

Out here, the above described scenario was achieved using the Client Callback feature introduced in ASP.NET 2.0. I found that a good amount of code related to this feature can be embedded inside a custom control such that it is easy to use. Moreover, if we use callback a number of times on a page, it would reduce lots of code. So, I tried to develop a "user friendly" custom control to use the Client Callback feature.

Background

In my current project, we had a scenario where different manufacturing parts were categorized (because of the hierarchical structure in the categorization, we decided to go with a tree view control). On selection of any one part (node), we were supposed to show the status and the data related to it in a grid placed on the same page. Performance was one of the major demands from the client. So, based on the needs, we decided to go with the Client Callback feature. The sample is based on this experience of mine.

Using the code

First, the important code parts of the custom control:

Apart from inheriting the control from WebControl, we also inherit it from ICallbackEventHandler.

C#
public class MyCustomCallBackControl : WebControl, ICallbackEventHandler {}

The OnInit() method of the control is overridden. The callback scripts related to the control are embedded here.

C#
// OnInit was overriden in order to attach a callback handler to the control
protected override void OnInit(EventArgs e)
{
     base.OnInit(e);
            
     string callback = Page.ClientScript.GetCallbackEventReference(this, "input", 
                       string.Concat(ID, "OnSuccess"), "context");
     Page.ClientScript.RegisterClientScriptBlock(typeof(MyCustomCallBackControl), 
                       ID, string.Concat("function ", ID, 
            "Callback(input, context) { ", callback, "; }"), true);
     //Above line - Script added during runtime:
     //function MyCustomCallBackControl1Callback(input, context) 
     //{      
     //    WebForm_DoCallback('MyCustomCallBackControl1',
     //          input,MyCustomCallBackControl1OnSuccess,context,null,false);      
     //}

     //General meaning of it:
     // WebForm_DoCallback(eventTarget, eventArgument, eventCallback, 
     //                    context, errorCallback, useAsync)
}

We will need to write the GetCallBackResult and RaiseCallBackEvent methods related to implement the ICallbackEventHandler interface.

C#
// Event handler for code logic at server side on client-callback
// Event bubbling done here 
public event EventHandler MyCallBackEvent;
public void RaiseCallbackEvent(string eventArgument)
{
      argumentParameter = eventArgument;
      if (MyCallBackEvent != null)
      {
          MyCallBackEvent(this, EventArgs.Empty);
      }
}

public string GetCallbackResult()
{
      //Returns back the output set during the callback
      return renderedOutput;
}

The Client Callback custom control is now ready to use.

We will now work on how to use the control on our web page. We drag drop the control on the page, and define the code-behind handler for it, basically, the server code that will run when the callback control is called.

C#
// Bubbled event for Callback control placed
// One can handle the operations required during the callback out here.
protected void CallBackControl_Perform(object sender, EventArgs e)
{
    DataTable dt = RetrieveDataTable(((
      MyCustomControls.MyCustomCallBackControl)sender).ArgumentParameter);
    gvTest.DataSource = dt;
    gvTest.DataBind();

    //Setting of the response output for callback
    using (System.IO.StringWriter sw = new System.IO.StringWriter())
    {
        gvTest.RenderControl(new HtmlTextWriter(sw));
        ((MyCustomControls.MyCustomCallBackControl)sender).RenderedOutput = sw.ToString();
    }
}

In our sample, we will bind the tree nodes to this callback control. This is done using JavaScript.

C#
//Client Side callback event attached
tNode.NavigateUrl = "javascript:OnNodeClick('" + tNode.Value + "');";

We are just left with defining the JavaScript functions that are attached to the custom callback control. The functions will be bound in the OnNodeClick method defined above.

JavaScript
//Node Callback Click Event
function OnNodeClick(nodeID)
{         
    // Method name to call has a fixed naming convention
    // CustomCallbackControl name + "Callback" 
        // Parameters to the function would be:
            // 1st : Input 
            // 2nd : Context                     
    MyCustomCallBackControl1Callback(nodeID, null); 
}        

// Function name has a fixed naming convention
// CustomCallbackControl name + "OnSuccess"
function MyCustomCallBackControl1OnSuccess(responseText) 
{       
    // Based on responseText, action taken on client side     
    document.getElementById("tdGridView").style.display = "block";
    document.getElementById("gvTest").outerHTML = responseText;   
}

We are finished with using the control now. The naming conventions for the JavaScript functions are defined, and need to be given accordingly.

Points of interest

Performance came out really good, that too with a simple and sleek UI. It was a good experience learning the comparisons and differences between using an UpdatePanel and a callback control.

Making it a custom control helped a lot. Even a beginner can use it without knowing much of what is happening inside it (it can be used multiple times on the same page). The control was easy to use and came out to be a good weapon in my Web stock! :)

History

  • 19th December, 2008: Initial post.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Intuit India
India India


A software professional for more than 17+ years building solutions for Web and Desktop applications.

Currently working at Intuit India.

Website: Learn By Insight
Github: Sandeep Mewara
LinkedIn: Sandeep Mewara

Strongly believe in learning and sharing knowledge.



Comments and Discussions

 
GeneralMy vote of 5 Pin
Savalia Manoj M18-Nov-12 16:46
Savalia Manoj M18-Nov-12 16:46 
GeneralMy vote of 1 Pin
David.jos12323-Jun-12 5:35
David.jos12323-Jun-12 5:35 
GeneralRe: My vote of 1 Pin
thatraja5-Aug-12 1:02
professionalthatraja5-Aug-12 1:02 
QuestionThis is not working in Mozilla Pin
Srinvias Ganta29-Jun-11 5:42
Srinvias Ganta29-Jun-11 5:42 
AnswerRe: This is not working in Mozilla Pin
Sandeep Mewara29-Jun-11 20:13
mveSandeep Mewara29-Jun-11 20:13 
GeneralMy vote of 5 Pin
Luc Pattyn11-Jun-11 5:09
sitebuilderLuc Pattyn11-Jun-11 5:09 
GeneralMy vote of 5 Pin
Ramalinga Koushik25-Feb-11 21:24
Ramalinga Koushik25-Feb-11 21:24 
GeneralGreat work! Pin
Matt Esterak10-Aug-09 19:03
Matt Esterak10-Aug-09 19:03 
AnswerRe: Great work! Pin
Sandeep Mewara7-Jan-10 22:23
mveSandeep Mewara7-Jan-10 22:23 
GeneralCompare to PageMethod Pin
bitseeker26-Apr-09 8:34
bitseeker26-Apr-09 8:34 
AnswerRe: Compare to PageMethod Pin
Sandeep Mewara7-Jan-10 22:22
mveSandeep Mewara7-Jan-10 22:22 
GeneralMy vote of 2 Pin
ProJester115-Jan-09 11:07
ProJester115-Jan-09 11:07 
AnswerRe: My vote of 2 Pin
Sam DoLittle19-Jan-09 19:12
Sam DoLittle19-Jan-09 19:12 
Generalnot Pin
mohamedgamal14-Jan-09 7:59
mohamedgamal14-Jan-09 7:59 
AnswerRe: not Pin
Sandeep Mewara18-Jan-09 19:08
mveSandeep Mewara18-Jan-09 19:08 
QuestionWhy Not Use a Page Method? Pin
nickyt13-Jan-09 2:34
nickyt13-Jan-09 2:34 
AnswerRe: Why Not Use a Page Method? Pin
Sandeep Mewara13-Jan-09 21:20
mveSandeep Mewara13-Jan-09 21:20 
GeneralVery Nice! Pin
JimWhite_Aus12-Jan-09 23:02
JimWhite_Aus12-Jan-09 23:02 
AnswerRe: Very Nice! Pin
Sandeep Mewara13-Jan-09 21:21
mveSandeep Mewara13-Jan-09 21:21 
GeneralUpdatePanel Pin
gstolarov31-Dec-08 13:17
gstolarov31-Dec-08 13:17 
AnswerRe: UpdatePanel Pin
Sandeep Mewara4-Jan-09 20:49
mveSandeep Mewara4-Jan-09 20:49 
GeneralRe: UpdatePanel Pin
gstolarov5-Jan-09 3:53
gstolarov5-Jan-09 3:53 
AnswerRe: UpdatePanel Pin
Sandeep Mewara5-Jan-09 8:52
mveSandeep Mewara5-Jan-09 8:52 
GeneralExcellent article! Pin
Stuart_Mic24-Dec-08 19:56
Stuart_Mic24-Dec-08 19:56 
GeneralRe: Excellent article! Pin
Sandeep Mewara29-Dec-08 17:26
mveSandeep Mewara29-Dec-08 17:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.