ASP.NET 2.0 Script CallBack (Ajax like)

Learn about the new ASP.NET 2.0 feature which allows you to do CallBack (similar to PostBack) on a form without reloading the page. This technique similar to Ajax uses the ICallbackEventHandler interface.

You probably already know what Ajax does, or maybe not, but what’s certain is that you heard about Ajax because much fuss is created around it on the web.

In this tutorial you’re going to learn a very interesting technique of combining client-side JavaScript with server-side ASP.NET 2.0. More exactly, we’re going to implement a simple rating system (a listbox and a button) which can be used to rate content on websites. But there’s something special about it: when the visitor clicks the button to submit the rating, the page will not reload, but the rating will be quietly sent to the server. From the server-side you can then do whatever you want with that value. You’re probably going to put it in a database. After the server finished adding the rating to the database, a client-side event will fire which you can use to notify the visitor with a message on the page “Content rated successfully!”. But once again without any page refresh. Everything works like in a Windows forms application.

This can be accomplished with Ajax, but we’re not going to use Ajax in this tutorial. We’re going to use a new technique implemented in ASP.NET 2.0 (you’ll have to find an alternative if you’re using ASP.NET 1.1): ICallbackEventHandler. This technique is very simple, and very appropriate for what we are trying to do. There are multiple examples on the web that accomplish a similar objective to the one in this tutorial, but the code is messier. This code is tested and works without problems in Internet Explorer and Firefox, so the major browsers are covered.

First, let’s place the HTML tags we’re going to use:

<p>Please click to rate (no refresh):</p>
<select runat="server" id="selRate">
   <option value="Poor">Poor</option>
   <option value="Mediocre">Mediocre</option>
   <option value="Fair" selected="selected">Fair</option>
   <option value="Good">Good</option>
   <option value="Excellent">Excellent</option>
</select>
<input type="button" runat="server" id="btnRate" value="Rate" />
<br /><br />
<div id="Result"></div>

As you can see above, we have a listbox from where the visitor can choose a rating. Then the btnRate button is pressed, but there is no onclick attribute because we will set the onClick attribute from server side.

Below we have the Result div, which will be used for displaying the result of adding the vote. The message inside the Result div will be set using server-side code.

Now let’s move to the C# code-behind. First modify the class declaration of the page to include the ICallbackEventHandler interface, like in the example below:

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

Moving on, add the following two lines in the Page_Load event:

string CallbackRef = Page.ClientScript.GetCallbackEventReference(this, "document.getElementById('selRate').value", "RateContent", "null");

btnRate.Attributes["onclick"] = String.Format("javascript:{0}", CallbackRef);

What’s important for you to understand from these two lines is that on the first line a Javascript function is actually created and stored in a string.

The parameters passed to GetCallbackEventReference() which should concern you are document.getElementById('selRate').value which is the value we want to retrieve from the client side (the value of the selected value in the listbox which is the actual rating) and RateContent which is the name of the JavaScript event that’s going to be called back on the client side when the server side finished its job.

The second line adds the onclick attribute we talked about earlier, to the btnRate button, with a call to the function that’s stored inside CallbackRef. So basically we’re creating some JavaScript code from the server-side, so that when the button is clicked, the function stored inside CallbackRef is called.

We’re done with the code in the Page_Load event. Now we have one more thing to do in the server-side code: a virtual method
named RaiseCallbackEvent where you can do your server-side coding, such as adding the vote to the database. Here’s how the method looks like:

public virtual string RaiseCallbackEvent(string eventArgument)

{

   // Here we will store the result of adding the vote, which will be passed to the client side code

   string VoteResult;


   // TODO HERE: Add the vote to the database or your option of storing data


   // We'll pretend the vote was added to the database and everything was successful

   VoteResult = "Your vote of <i>" + eventArgument + "</i> was registered successfully!";


   return VoteResult;

}

Now I have to confess something: the above method - RaiseCallbackEvent(string eventArgument)- only works in ASP.NET 2.0.50215 (.NET Framework Beta). If you try to use it in the final version of ASP.NET (2.0.50727), you will get an error similar to the following: ‘_Default’ does not implement interface member ‘System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(string)’.

The reason for that you can find in a topic at the MSDN forums. So if you’re running the final version of ASP.NET 2.0, you’ll have to use the following longer piece of code instead:

private string _callbackArg;


void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)

{

   _callbackArg = eventArgument;

}


string ICallbackEventHandler.GetCallbackResult()

{

   return RaiseCallbackEvent(_callbackArg);

}



protected virtual string RaiseCallbackEvent(string eventArgument)

{

   // Here we will store the result of adding the vote, which will be passed to the client side code

   string VoteResult;


   // TODO HERE: Add the vote to the database or your option of storing data


   // We'll pretend the vote was added to the database and everything was successful

   VoteResult = "Your vote of <i>" + eventArgument + "</i> was registered successfully!";


   return VoteResult;

}

As you probably figured out, the eventArgument argument contains the value originally pased by the client-side, which in our case is the value of the selected listbox item. I’m not going to provide source code on how to add the vote in the database on this tutorial since it would be out of its original scope. But we’ll pretend we did and set the VoteResult string to a message shouting success.

We’re almost done, but there’s one more step: the JavaScript function which is going to update the page saying the vote was added successfully. So back to client-side, add the following script:

<script type="text/javascript">
   function RateContent(result, context)
   {
      document.getElementById('Result').innerHTML = result;
   }
</script>

Remember the RateContent attribute which we passed to GetCallbackEventReference method back in the server-side C# code and we said it’s the name of the JavaScript event which is going to be called on the client-side? Well this is it – this is the function that’s called after the server-side has completed the work. And as you can see, in this function we simply set the content of a div with the success message returned by the server-side code.

This is all you need to do to accomplish the wonderful functionality of submitting a form, or in our case adding a vote to a database, without refreshing the page. Most of the visitors hate when the page refreshes or a popup shows just for the simple task of rating an article, therefore this kind of functionality will be welcomed on your website. And thanks to ASP.NET 2.0 it can be accomplished quite easily.

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top