Tutorial RSS
 
Navigator: Home - Advanced - Creating a Poll with AJAX, SQL and LINQ in C#

Creating a Poll with AJAX, SQL and LINQ in C#

This tutorial will show you how to create an online voting system which will take advantage of AJAX and LINQ to allow users to quickly and easily vote for their favorite Political candidate, and be shown who is currently the front-runner. C#

Looking for the VB.NET version? Click here!

Looking for more .NET Database Tutorials? Click Here!

We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.


Polling and voting systems can be very useful when wanting to survey for data. Visitors tend not to mind giving their opinion on a quick poll, as it is quick and there is no need to reveal any personal information.
In this tutorial, we will be looking at how we can create a poll with a SQL database, LINQ and AJAX.

The first thing we need to do is create the database. We will have a poll on peoples' political views- Obama or McCain. We will create a SQL database with one table and two columns - id and vote. People will be able to submit their votes via a form with a radiobutton list, so once we have our database set up, we can begin on the ASPX form:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Literal ID="litResults" runat="server" visible="false"/><br />
Who is your favorite Candidate?<br />
<asp:RadioButtonList ID="radVote" runat="server">
<asp:ListItem>Obama</asp:ListItem>
<asp:ListItem>McCain</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="butVote" runat="server" Text="Vote"
onclick="butVote_Click" /><br />
<asp:Label ID="lblStatus" runat="server" /><br />
<asp:Button ID="butResults" runat="server" Text="Show Results"
onclick="butResults_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="PollDataContext" EnableInsert="True" TableName="tblPolls">
</asp:LinqDataSource>
</form>


Here, you'll notice we have a LinqDataSource. We added this to communicate with our LINQ to SQL Classes, which we add by right-clicking our project in Solution Explorer and choosing Add New Item, LINQ to SQL Classes. We drag our table from Server Explorer to the design view, and then save. VS will create the class and methods for us.
We have a Radio Button List on our page, and two buttons, as well as a label and a literal control. The literal will be used to display the results of the poll, and the label will be used for any validation and errors. The two buttons will be to submit the vote and to read current results.

Notice also that our buttons have been assigned methods on the click events. The first, looks something like this:

protected void butVote_Click(object sender, EventArgs e)
{
if (radVote.SelectedItem == null)
lblStatus.Text = "Please vote.";
else
countVote(radVote.SelectedItem.ToString());
}


This simple method checks to see if an option has been selected. If it has, we call another method to add the vote to the database:

protected void countVote(string theVote)
{
try
{
string conn = ConfigurationManager.ConnectionStrings["PollConnectionString"].ToString();
PollDataContext context = new PollDataContext(conn);

tblPoll pt = new tblPoll();
pt.vote = theVote;
context.tblPolls.InsertOnSubmit(pt);
context.SubmitChanges();

lblStatus.Text = "Thank you for your vote.";
readData();
}
catch
{
lblStatus.Text = "Sorry, unable to process request. Please try again.";
}
}

We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!


Here, we use a Try...Catch to provide some error prevention. We use LINQ to add the selected option to the database. Finally, we create a method that will read the results from the database:

protected void readData()
{
string conn = ConfigurationManager.ConnectionStrings["PollConnectionString"].ToString();
PollDataContext context = new PollDataContext(conn);

tblPoll pt = new tblPoll();

var votes = from vote in context.tblPolls select vote;

int mCount;
int oCount;
mCount = 0;
oCount = 0;

foreach (var vote in votes)
{
if (vote.vote == "McCain")
mCount++;
else if (vote.vote == "Obama")
oCount++;
}

double theTotal;
theTotal = mCount + oCount;
double mPercent;
double oPercent;
mPercent = (mCount/theTotal)*100;
oPercent = (oCount/theTotal)*100;

litResults.Visible = true;
litResults.Text = "Obama: " + oCount + " votes (" + oPercent + "%).<br />";
litResults.Text = litResults.Text + "McCain: " + mCount + " votes (" + mPercent + "%).<br /><br />";
}


Again we use LINQ to make a selection of all the data from the database, then we loop through it and count how many votes there are for each candidate. We also make a simple calculation to work out and display the percentage of votes for each one. We also code the other button, simply calling the readXML method:
protected void butResults_Click(object sender, EventArgs e)
{
readData();
}

Try Server Intellect for Windows Server Hosting. Quality and Quantity!


The entire code-behind will look like this:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void butVote_Click(object sender, EventArgs e)
{
if (radVote.SelectedItem == null)
lblStatus.Text = "Please vote.";
else
countVote(radVote.SelectedItem.ToString());
}

protected void countVote(string theVote)
{
try
{
string conn = ConfigurationManager.ConnectionStrings["PollConnectionString"].ToString();
PollDataContext context = new PollDataContext(conn);

tblPoll pt = new tblPoll();
pt.vote = theVote;
context.tblPolls.InsertOnSubmit(pt);
context.SubmitChanges();

lblStatus.Text = "Thank you for your vote.";
readData();
}
catch
{
lblStatus.Text = "Sorry, unable to process request. Please try again.";
}
}

protected void readData()
{
string conn = ConfigurationManager.ConnectionStrings["PollConnectionString"].ToString();
PollDataContext context = new PollDataContext(conn);

tblPoll pt = new tblPoll();

var votes = from vote in context.tblPolls select vote;

int mCount;
int oCount;
mCount = 0;
oCount = 0;

foreach (var vote in votes)
{
if (vote.vote == "McCain")
mCount++;
else if (vote.vote == "Obama")
oCount++;
}

double theTotal;
theTotal = mCount + oCount;
double mPercent;
double oPercent;
mPercent = (mCount/theTotal)*100;
oPercent = (oCount/theTotal)*100;

litResults.Visible = true;
litResults.Text = "Obama: " + oCount + " votes (" + oPercent + "%).<br />";
litResults.Text = litResults.Text + "McCain: " + mCount + " votes (" + mPercent + "%).<br /><br />";
}

protected void butResults_Click(object sender, EventArgs e)
{
readData();
}
}




Looking for the VB.NET version? Click here!

Looking for more .NET Database Tutorials? Click Here!

Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!


Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!

411asp.net123aspxDotNetFreaksServer Intellect