Click here to Skip to main content
14,693,352 members
Articles » Web Development » ASP.NET » General
Posted 18 Nov 2007


52 bookmarked

Creating a Poll System Using ASP.NET 2.0 Callbacks

Rate me:
Please Sign up or sign in to vote.
4.34/5 (21 votes)
18 Nov 2007
An article on how to create an AJAX enabled polling system using ASP.NET client callbacks.


Creating a poll on your website enables you to find out more about the interests of the user. I recently added a weekly poll system to KofeeKoder. In this article, I will explain how to create an AJAX enabled polling system using ASP.NET client callbacks.

Database Schema

The database schema consists of only two tables:

  1. PollQuestions: This table holds all the questions for the poll
  2. PollChoices: This table holds the choices of the poll questions

Take a look at the schema shown below:

Image 1

Stored Procedure



SELECT @pqID = MAX(PollQuestionID) FROM PollQuestions

SELECT q.PollQuestionID,q.[Text] AS PollText,c.PollChoiceID,
  c.[Text] ChoiceText,c.Total FROM PollQuestions q JOIN PollChoices c
  ON q.PollQuestionID = c.PollQuestionID WHERE q.PollQuestionID = @pqID


Poll Control Architecture

I wanted to create the polling user control in such a way that it does not depend on the page. Let's take a look at the class diagram below:

Image 2

Now, let me explain each class in detail:

  • IPoll<code>: IPoll is an interface which will be used by all the polling classes
  • WeeklyPoll: This is the class responsible for creating weekly polls. It implements the IPoll interface
  • PollQuestion: This is an entity class which maps to the PollQuestions table in the database
  • PollChoice: This is an entity class which maps to the PollChoices table in the database
  • PollTableHelper: This is a helper class which is used to generate dynamic HTML tables
  • ControlToHtmlConvertor: This class contains helper methods to convert a control into pure HTML
  • DataAccess: This class serves as the DataAccess class and is used to INSERT and SELECT polls from the database


Let's dive into the implementation details. We will see few important classes in this article. For complete implementation, you can use the code given below in this article.


The IPollInterface is implemented by all classes that want to expose polling functionality.

public interface IPoll
        string Create();
        string GetStats();


WeeklyPoll is one of the classes that implements the IPoll interface. The implementation is given below:

public class WeeklyPoll : IPoll
        public string Create()
            PollQuestion poll = PollQuestion.GetPoll();
            return PollTableHelper.GenerateTableForPoll(poll);

        public string GetStats()
            PollQuestion poll = PollQuestion.GetPoll();
            return PollTableHelper.GetPollStats(poll);

I will not discuss the PollTableHelper class since the code is simply used to build a table. You can download the complete code available for download at the top of this article and view the implementation.


The PollControl.ascx is a user control which is used to display the poll to the user. Let's first take a look at the HTML code for the PollControl.ascx control.

Yup, that's it!

Now, let's take a look at the code behind:

protected void Page_Load(object sender, EventArgs e)

        private void RegisterCallbacks()

        string sbReference = Page.ClientScript.GetCallbackEventReference
            (this, "arg", "ReceiveServerData", "context");
        string cbScript = String.Empty;
        // check if the script is already registered or not
        if (!Page.ClientScript.IsClientScriptBlockRegistered("CallServer"))
            cbScript = @" function CallServer(arg,context) 
                { " + sbReference + "} window.setTimeout(CallServer,100); ";
                (this.GetType(), "CallServer", cbScript, true);


In the code above I am simply registering the callbacks. If you are interested in learning more about how to register the page/usercontrol to use callbacks, then take a look at this article.

Everything about registering the callback method is the same except the call to the window.setTimeout function. I made this call so I can fire the CallServer method right after registering it on the page. I know you must be thinking why not simply fire CallServer('', '') at the end of the callback registration process. Unfortunately, this technique does not work since the CallServer takes arguments from the page.

For the callbacks to work, you must implement the ICallbackEventHandler interface as shown below:

public partial class PollControl : 
    System.Web.UI.UserControl, ICallbackEventHandler

The ICallbackEventHandler interface consists of two methods namely, GetCallbackResult and RaiseCallbackEvent. Let's see the implementation below:

public void RaiseCallbackEvent(string eventArgument)
            // update the polls
            string[] selection = eventArgument.Split(':');
            if (selection.Length > 1)
                // create a cookie for the user

The RaiseCallbackEvent is fired when the user casts the vote using the "Vote" button. I check if the user has selected some choice and if so, update the choice in the database. After updating the choice I also create a cookie so that the user will not be able to vote for some time.

I could have also used IP address to keep track of which user has given a vote but using IP address has some disadvantages. If a person is on a LAN which is behind a firewall then the vote given by him will be the vote for the entire LAN since computers connected to the LAN are behind a firewall giving them the same IP address.

The CreatePollCookie is used to create HttpCookie:

private void CreatePollCookie()
        HttpCookie pollCookie = new HttpCookie("PollCookie");
        pollCookie.Value = "PollCookie";

      pollCookie.Expires = DateTime.Now.AddDays(7);

The method GetCallbackResult is fired right before sending the contents to the client.

public string GetCallbackResult()
            string result = String.Empty;
            IPoll poll = new WeeklyPoll();

            if (DoesCookieExists())
                result = poll.GetStats();
                result = poll.Create();

            return result;

The method DoesCookieExists ensures that if the client has already voted, then you need to show her or him the vote statistics, otherwise show the poll. This is performed by checking for the existence of the cookie.

private bool DoesCookieExists()
          if (Request.Cookies["PollCookie"] != null) return true;
          else return false;

The JavaScript Code

All the JavaScript code is stored in the Site.js file. All the pages of the website must have a reference to the JS file for the poll control to work.

function vote()
    var pollWidget = document.getElementById("divPoll");
    var inputElements = pollWidget.getElementsByTagName("INPUT");
    var userSelection;

    for(i=0; i<inputElements.length;i++)
                userSelection = inputElements[i].id;

    // call the server method to note the changes

function ReceiveServerData(rValue)
    document.getElementById("divPoll").innerHTML = rValue;

function isRadioButton(target)
    return target.type == 'radio';

You can see the polling control live in action on the upper right hand side of the screen. Hey! When you are there, please do cast your vote!

I hope you liked the article, happy programming!


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.

I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

GeneralMy vote of 2 Pin
techiebuilds19-Apr-13 4:09
Membertechiebuilds19-Apr-13 4:09 
GeneralMy vote of 3 Pin
alexfire25-Aug-10 5:51
Memberalexfire25-Aug-10 5:51 
GeneralMy vote of 4 Pin
rvargas152-Jul-10 10:36
Memberrvargas152-Jul-10 10:36 
Generalsos! compilation error Pin
the bill8-Feb-08 12:37
Memberthe bill8-Feb-08 12:37 
GeneralRe: sos! compilation error Pin
the bill8-Feb-08 13:55
Memberthe bill8-Feb-08 13:55 
QuestionNot able to run code Pin
shahzadsb005-Dec-07 2:20
Membershahzadsb005-Dec-07 2:20 
GeneralRe: Not able to run code Pin
azamsharp5-Dec-07 6:37
Memberazamsharp5-Dec-07 6:37 
AnswerRe: Not able to run code Pin
Antony M Kancidrowski15-May-08 1:49
MemberAntony M Kancidrowski15-May-08 1:49 
Generalsuggestion Pin
wissam14-Dec-07 20:11
Memberwissam14-Dec-07 20:11 
GeneralRe: suggestion Pin
azamsharp5-Dec-07 6:43
Memberazamsharp5-Dec-07 6:43 
GeneralNice article Pin
dotnetchick23-Nov-07 3:16
Memberdotnetchick23-Nov-07 3:16 
QuestionStart Page [modified] Pin
gluvce21-Nov-07 22:53
Membergluvce21-Nov-07 22:53 
AnswerRe: Start Page Pin
azamsharp22-Nov-07 5:41
Memberazamsharp22-Nov-07 5:41 
NewsRe: Start Page [modified] Pin
gluvce23-Nov-07 0:01
Membergluvce23-Nov-07 0:01 
GeneralRe: Start Page Pin
azamsharp23-Nov-07 6:17
Memberazamsharp23-Nov-07 6:17 
GeneralRe: Start Page Pin
gluvce23-Nov-07 9:34
Membergluvce23-Nov-07 9:34 
GeneralRe: Start Page Pin
wissam14-Dec-07 20:42
Memberwissam14-Dec-07 20:42 
GeneralRe: Start Page Pin
azamsharp5-Dec-07 6:45
Memberazamsharp5-Dec-07 6:45 
QuestionDoubt.... Pin
Sidhaarthan Asaithambi20-Nov-07 16:11
MemberSidhaarthan Asaithambi20-Nov-07 16:11 
AnswerRe: Doubt.... Pin
azamsharp20-Nov-07 16:52
Memberazamsharp20-Nov-07 16:52 
Generalafdsafd Pin
nngocqui19-Nov-07 20:51
Membernngocqui19-Nov-07 20:51 

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.