|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionCreating 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 SchemaThe database schema consists of only two tables:
Take a look at the schema shown below:
Stored ProcedureCREATE PROCEDURE usp_GetLastestPoll
AS
DECLARE @pqID int
SELECT @pqID = MAX(PollQuestionID) FROM PollQuestions
PRINT @pqID
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
GO
Poll Control ArchitectureI 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:
Now, let me explain each class in detail:
ImplementationLet'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. IPollInterfaceThe public interface IPoll
{
string Create();
string GetStats();
}
WeeklyPoll
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 PollControl.ascxThe 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)
{
RegisterCallbacks();
}
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); ";
Page.ClientScript.RegisterClientScriptBlock
(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 For the callbacks to work, you must implement the public partial class PollControl :
System.Web.UI.UserControl, ICallbackEventHandler
The public void RaiseCallbackEvent(string eventArgument)
{
// update the polls
string[] selection = eventArgument.Split(':');
if (selection.Length > 1)
{
PollQuestion.Update(Int32.Parse(selection[0]),
Int32.Parse(selection[1]));
// create a cookie for the user
CreatePollCookie();
}
}
The 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 private void CreatePollCookie()
{
HttpCookie pollCookie = new HttpCookie("PollCookie");
pollCookie.Value = "PollCookie";
pollCookie.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(pollCookie);
}
The method public string GetCallbackResult()
{
string result = String.Empty;
IPoll poll = new WeeklyPoll();
if (DoesCookieExists())
{
result = poll.GetStats();
}
else
{
result = poll.Create();
}
return result;
}
The method private bool DoesCookieExists()
{
if (Request.Cookies["PollCookie"] != null) return true;
else return false;
}
The JavaScript CodeAll 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++)
{
if(isRadioButton(inputElements[i]))
{
if(inputElements[i].checked)
{
userSelection = inputElements[i].id;
break;
}
}
}
// call the server method to note the changes
CallServer(userSelection,'');
}
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!
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||