German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


Client Callback in the Website Registration Page

Written by omerkamal on Jul 02, 2007
Create functionality in your Registration Page for avalibilty of the username. How to create a Client Callback in ASP .NET ? Getting Response from the Server without a Page Post Back

What is a Page Post Back?                                        Download: TheCallBackMethod.Zip

You opened a browser, typed a web page URL and it opened your desired page for you; it shows you all the information of the page. Generally speaking, these all information is saved on the web server.

Some time you just don’t read stuff on the web sites but you really interact with them. For this you need to send or submit data to the server and it does the desired job for you. A good example could be like you registering yourself to some online community like MySpace or MSN.

 In ASP .NET “Post back” is a method or a way through which data is sent or submitted to the web server. This Post back could be either a “Partial Post back (PPB)” or a “Complete Page Post back”. Partial Post back is something new in the web development. The term PPB is actually invention of the AJAX era.

Whatever type of post back we talk about, the end result is the same: “Server to Human Interaction”. Whereas, in the behavior the both process cycles are very different.  

We won’t talk about the difference of these two types of Post Back methods. Rather we will introduce you a different way of talking to the server.

What is a Client Callback?

In the post back the requests are responded through the complete cycle of page generation. In the call back method data is processed independent to the page life cycle. How?

There is a good example: as earlier we talked about popular web sites registration’s procedure like MySpace and MSN, there is a way that you can check the availability of your desired Username (you will also find this at our web site Dotnet-Friends.com registration page). You will notice that by Clicking the Button “Available?” page is not refreshed but your data was submitted and you got a response from the Web Server.

So what is the Magic? Be careful don’t mix this with AJAX now, even that AJAX is using the same technology. But it keeps you blind of what happens in the back ground :)

Let’s now see how it works! We are going to see a Practical example for that. This is what we also adopted at our registration page.

Components of Client Callbacks

Creating an ASP.NET page that implements client callbacks is similar to creating any ASP.NET page, with a few these differences. The page's server code must:

·         Implement the ICallbackEventHandler interface. You can add this interface declaration to any ASP.NET Web page.

·         Provide an implementation for the RaiseCallbackEvent(String) method. This method will be invoked to perform the callback on the server.

·         Provide an implementation for the GetCallbackResult() method. This method will return the callback result to the client.

In addition, the page must contain three client script functions that perform the following actions:

·         One function calls a helper method that performs the actual request to the server. In this function, you can perform custom logic to prepare the event arguments first, and then you can send a string as a parameter to the server-side callback event handler.

·         Another function receives (is called by) the result from the server code that processed the callback event, accepting a string that represents the results. This is called the client callback function.

·         A third function is the helper function that performs the actual request to the server, which is generated automatically by ASP.NET when you generate a reference to this function using the GetCallbackEventReference method in server code.

Code Example:

Create a test Project. Let us call it TheCallbackMethod. Add an ASP .NET Server Control and two simple HTML Control/Tags to default.aspx page:

1.       An ASP .NET  Textbox name its Id “tbSendMessage”

2.       An HTML Button name its Id "btnSender"

3.       An HTML Span Tag name its Id "Message"

We are using HTML tags in the page so we can cater the possibility of post back of Controls which is basic behavior of ASP .NET Controls.  The code within the page Form tag will look like this:

<div style="margin-top:100px; text-align:center">

  <table>

     <tr>

       <td>

         <asp:TextBox ID="tbSendMessage" runat="server">asp:TextBox>

       td>

       <td>

         <input type="button" id="btnSender" value="Available?" />

       td>

     tr>

     <tr>

       <td colspan="2" align="left">

          <span id="Message"

           style="font-size: 12; font-weight: bold; color: Red">span>

       td>

     tr>

  table>

div>

Ok, now we are ready. We have to add some code to the Server side and the Client side both. For the Server side we are going to use C# and for the Client side is JavaScript.

Add an event reference for the Button onClick event for the btnSender.

<input type="button" id="btnSender" value="Available?" onclick="LookName();" />

Right Click the Page and Click the “Code View”.   Inherit your Page also from System.Web.UI.IcallbackEventHandler Class.

Your new Class signatures will look like this:

public partial class _Default : System.Web.UI.Page , System.Web.UI.ICallbackEventHandler

Now, to add JavaScript to the Page we will use Page_Load event.

protected void Page_Load(object sender, EventArgs e)

{

   ClientScriptManager cm = Page.ClientScript;

   String cbReference =

   cm.GetCallbackEventReference(this,

          "arg","ReceiveServerData", "context");

   String callbackScript =

          "function CallServer(arg, context) {" + cbReference + "; }";

   cm.RegisterClientScriptBlock(this.GetType(),

          "CallServer", callbackScript, true);

   cm.RegisterClientScriptBlock(this.GetType(),

                    "SendValue", @"function LookName(){

                     CallServer(document.getElementById('"

                  + tbSendMessage.UniqueID + @"').value,'')}", true);

   cm.RegisterClientScriptBlock(this.GetType(),

                 "ReceiveData", @"function ReceiveServerData(context)

                 {Message.innerText = context;}", true);

  

        }

This will add three JavaScript Functions to the Page. Add following C# code after the Page_Load .

protected String returnValue = "User Name is Available.";

public void RaiseCallbackEvent(String eventArgument)

{

     if (eventArgument.Length == 0)

           returnValue = "Enter a User Name!";

     else

      {

         string[] names = new string[]

                  { "name1", "name2", "name3", "name4", "name5"};

          foreach (string st in names)

          {

             if (st.ToLower() == eventArgument.ToLower())

                   returnValue = "User Name is Taken.";

          }

      }

 }

 public string GetCallbackResult()

 {

      return returnValue;

 }  

Now, execute your Project. Try some Text in the Textbox. Anything else then what we have in the Array list will be permitted. You will notice that for this all activity our page never refreshes.

If you are embeding the Callback method in your web page then probebly you are also using  the ASP .NET 2.0 Membership. For this you can do changings in your RaiseCallbackEvent method like this:

    public void RaiseCallbackEvent(String eventArgument)

    {

        if (eventArgument.Length == 0)

            returnValue = "Enter a User Name!";

        else

        {

            MembershipUserCollection mc = Membership.GetAllUsers();

            foreach (MembershipUser st in mc)

            {

                if (st.UserName.ToLower() == eventArgument.ToLower())

                    returnValue = "User Name is Taken.";

            }

        }

    }

Here you can download the Example Project. 

Download: TheCallBackMethod.Zip 

Visitors/Readers Comments
(for questions please use The Forum)



Vishnu Mahesh

nice one understandable

07/09/2007 05:44:44 UTC

Daniel
I was wondering if the button had to be html, could you just you an asp button?

13/09/2007 15:00:45 UTC

Omer Kamal
ASP Button will do autoPostback this is why HTML Button is requierd in this special senario.

14/09/2007 01:15:30 UTC

Daniel
But what if you don't want the AutoPostBack because of the flicker, hence the reason why I want to use javascript.

17/09/2007 10:02:49 UTC

Omer Kamal

JavaScript is only Client side scripting. To access data from the Server you will need a Server Side Script.

As discribed above there are two ways to access the Server Side Data.

  1. Postback
  2. Client CallBack

18/09/2007 01:28:56 UTC

Bipin Godase

It's good one but more clarification on server site scripting

 

13/11/2007 04:08:48 UTC

Stephan
very nice introduction, thanks!

13/01/2008 02:37:53 UTC

Wissam Bishouty
Daniel ask if he can use an asp button,

My answer he can use an asp button by using the onClientClick attribute of the asp button and he can call the javascript function by : onclientclick="LookName();" and at the end of the lookname function place the code : return false.

I hope this code helps you.
Best regards.


14/01/2008 00:09:10 UTC


I give some vb.net codes to represent this method:

 VB.NET

Partial Class clientscript
    Inherits System.Web.UI.Page
    Implements System.Web.UI.ICallbackEventHandler


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim cm As ClientScriptManager = Page.ClientScript
        Dim cn As String = cm.GetCallbackEventReference(Me, "arg", "ReceiveServerData", "context")
        cm.RegisterClientScriptBlock(Me.GetType, "callback", "function CallServer(arg,context) {" & cn & ";}", True)
        cm.RegisterClientScriptBlock(Me.GetType, "sendvalue", "function LookName(){ CallServer(document.getElementById('" & tbSendMessage.uniqueID & "').value); }", True)
        cm.RegisterClientScriptBlock(Me.GetType, "receiveData", "function ReceiveServerData(context){Message.innerText=context;}", True)
    End Sub

    Private returnValue As String
    Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
        Return returnValue
    End Function

    Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
        If eventArgument.Length = 0 Then
            returnValue = "Need a username"
        ElseIf eventArgument = "job" Then
            returnValue = "This name has Taken"
        Else
            returnValue = "Available Name"
        End If
    End Sub
End Class

14/01/2008 19:26:05 UTC

liubing

javascript is a better way!

but thanks a lot! and this fckeditor is nice!

15/01/2008 00:24:06 UTC

Tarik Guney
Thanks A lot, it is easy to understand and implement. Actually I was a little bit confused with that thing but now it is completely clarified.
Have a nice day.

15/01/2008 19:23:33 UTC

Tarik Guney
By the way, Sorry but this editor is too much for here, isn't it :)

15/01/2008 19:24:53 UTC

Mukundan

pls try to add comments regarding, what they r doing ?

Thank you

18/01/2008 21:47:02 UTC

Anil

THanks A LOT .

ITS A NICE IDEA !

29/01/2008 06:39:24 UTC

Srinivasan
Thanks for your article about ICallbackEventhandler

07/02/2008 05:23:33 UTC

Ravi
This is not working on firefox.

26/02/2008 00:30:45 UTC

Lars

How about  the ability to use this for an onclick for a listbox?

 

11/03/2008 07:09:08 UTC

web
can someone clarify the code in page load i couldnt understand it

18/03/2008 18:04:55 UTC

sherin

Very nice indeed.

24/03/2008 03:26:59 UTC

A1

the code returns an error for me at line 22 (object not defined), could some one tell me what's wrong

26/03/2008 01:22:50 UTC

dejawoo
I was trying to implement  ajax enabled custom server control using ajax.net library. as I know callback within asp.net is an alternative. what I can not find in ajax.net  it stipulates to make the callback methods  scope on page or webservice.  I mean I have to implement the method within my page or webservice. it s ok if I am the page developer. what I am trying to implment is the control. That method should be embedded within control and agnostic to page it lives. Could it be done in AJAX.net or I have to lean to ICallBack implementation in ASP.net

05/05/2008 05:34:34 UTC

Question
It appears that ICallbackHandler is not session based. I am using the form authentication. I open IE browser to login to a page implemented this callback. When I open Firefox to login to this page, the IE browser content is replaced with Firefox user content.
I am really upset about that.


-Any help on using this interface?  Thanks.

29/06/2008 16:26:29 UTC




Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)