Server Intellect

AJAX-Enabled Poll System using LINQ in VB.NET

Category: AJAX

AJAX-Enabled Web Poll System using LINQ to XML in ASP.NET with VB

Introduction

If you've ever seen or taken part in those polls on various websites which allow all users to cast their votes on a variety of subjects, then you know what this article is going to be about. Web polls can be a very good way of capturing a lot of data very easily. The data may not be 100% accurate, but seeing as they are so simple to take part in, they are likely to generate a lot of results.

In this article, we will be looking at how we can create a poll ourselves from scratch using Visual Studio.NET, and we can also implement a little AJAX in there to make the experience even quicker and easier for our visitors.
In this example, we are going to use an XML file to store the results of the poll and we will use an ASP.NET RadioButtonList control for the multiple-choice answer. The question we will be asking is, 'Who is your favorite Presidential Candidate?', which is a popular topic at the moment.
We will also provide an option to view the current results, complete with percentage of votes for each candidate.

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.

What we will learn in this article:

  • How to use an external XML file to store data;
  • How to retrieve data from an XML file and perform calculations.

Getting Started
To begin, let's start a new VB.net web application project in Visual Studio, and once opened, we can right-click on the project in Solution Explorer and then choose Add New Item.. XML File. Let's call it Poll.xml


[Click to enlarge]

We will use the following structure for the XML file, as we also want to capture the name of the voter:

<?xml version="1.0" encoding="utf-8"?>
<Poll>
<Vote>
<Name>Paul</Name>
<Choice>Obama</Choice>
</Vote>
<Vote>
<Name>Mike</Name>
<Choice>McCain</Choice>
</Vote>
</Poll>

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!

We add two sample votes to start the XML file off, and to keep it fair.
We are going to develop this as an AJAX Web Application, so let's go ahead and save the XML file and then move onto the ASPX page, where we will add a ScriptManager and an UpdatePanel:

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

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>
</form>

We will be also adding a Literal control to display the current results of the poll, which we'll name litResults; a TextBox for the name of the voter, which we'll name txtName; a RadioButtonList for the poll options, which we'll name radVote; a button to submit the vote; butVote, a label to provide any errors or status messages; lblStatus, and finally another button to show the current results; butResults.
All of these controls will be placed in the ContentTemplate of the UpdatePanel, like so:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Literal ID="litResults" runat="server" visible="false"/><br />
What is your name? <asp:TextBox ID="txtName" runat="server" /><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" /><br />
<asp:Label ID="lblStatus" runat="server" /><br />
<asp:Button ID="butResults" runat="server" Text="Show Results" />
</ContentTemplate>
</asp:UpdatePanel>

Notice that we hide the Literal control by setting its Visible attribute to false, and then we can set it to true in the code-behind when we assign a value. We also add the choices of the RadioButtonList using the ListItem tags - we do not set a default value; the user must choose one.
We are almost done with building the ASPX page, but we want to code the event handlers for the buttons. We can do this by going into design view and either double-clicking the buttons to add an onclick event handler, or clicking the button once and then clicking the Events button (Lightning bolt) in the Properties Window and double-clicking on the Click event. This is a good way of accessing all the events of a control.

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

Go ahead and create event handlers in the code-behind for both buttons. We should have something like this:

Protected Sub butVote_Click(ByVal sender As Object, ByVal e As EventArgs)

End Sub

Protected Sub butResults_Click(ByVal sender As Object, ByVal e As EventArgs)

End Sub

We will create separate methods; one to read the XML file and retrieve the current results, and the other to submit the vote to the XML file. Then we will call these methods from the button click event handlers.
Let's start with the countVote method, which will add a new entry to the XML file. We will use a Try..Catch to avoid as many errors as we can. Using LINQ to XML, we can load the XML file and then very easily add a new element with the values passed through the form. Finally, we save the new XML document, let the visitor know their vote was successfuly cast and call the other method to output the current results:

Protected Sub countVote(ByVal theVote As String)
Try
Dim xmlDoc As XDocument = XDocument.Load(Server.MapPath("Poll.xml"))

xmlDoc.Element("Poll").Add(New XElement("Vote", New XElement("Name", txtName.Text), New XElement("Choice", theVote)))

xmlDoc.Save(Server.MapPath("Poll.xml"))
lblStatus.Text = "Thank you for your vote."
readXML()
Catch
lblStatus.Text = "Sorry, unable to process request. Please try again."
End Try
End Sub

Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!

The reading of the results is a little more complex than adding. We will use LINQ to XML to first load the XML file and then make a selection of all the dat, which we will then loop through to count the number of votes for each candidate. We will then use these figures to calculate the percentage of votes each candidate has received. Finally, we output the results to the Literal control:

Protected Sub readXML()
Dim xmlDoc As XDocument = XDocument.Load(Server.MapPath("Poll.xml"))

Dim votes = From vote In xmlDoc.Descendants("Vote") _
Select Name = vote.Element("Name").Value, Vote = vote.Element("Choice").Value

Dim mCount As Integer = 0
Dim oCount As Integer = 0

For Each vote In votes
If vote.Vote = "McCain" Then
mCount += 1
ElseIf vote.Vote = "Obama" Then
oCount += 1
End If
Next vote

Dim theTotal As Double = mCount + oCount
Dim mPercent As Double = (mCount / theTotal) * 100
Dim oPercent As Double = (oCount / theTotal) * 100

litResults.Visible = True
litResults.Text = "Obama: " & oCount & " votes (" & oPercent & "%).<br />"
litResults.Text = litResults.Text & "McCain: " & mCount & " votes (" & mPercent & "%).<br />"
End Sub

We can simply call this method from the button click event of the results button, like so:

Protected Sub butResults_Click(ByVal sender As Object, ByVal e As EventArgs)
readXML()
End Sub

We can also do the same for the vote button, but we will add a little validation to this one. We don't want the user to be able to vote without selecting an option or entering their name, so we use a simple IF statement:

Protected Sub butVote_Click(ByVal sender As Object, ByVal e As EventArgs)
If txtName.Text = "" Then
lblStatus.Text = "Please enter your name."
ElseIf radVote.SelectedItem Is Nothing Then
lblStatus.Text = "Please vote."
Else
countVote(radVote.SelectedItem.ToString())
End If
End Sub

I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.

Running this web application now will allow us to submit votes on the poll, and also view the current results:

What we have Learned

We have learned how to create a voting system using LINQ to XML and AJAX.

Attachments



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!

Leave a Comment

Comments on this Article

Post a Comment
Name:
Website:
Email:
Comments:

#1 Chaitanya

Posted By: Chaitanya | 10.09.2008 at 4:09 AM

Good Article

#2 alex

Posted By: alex | 1.08.2009 at 10:59 PM

Great article ,we will be looking at how we can create a poll ourselves from scratch using Visual Studio.NET, and we can also implement a little AJAX in there to make the experience even quicker and easier for our visitors, programming required a lot of experience and knowledge to develop a project,

http://www.cyberdesignz.com/ , you can more information from this.

#3 Dulwan Baddewithana

Posted By: Dulwan Baddewithana | 4.08.2009 at 9:42 PM

Another good stuff

#4 zunisun

Posted By: zunisun | 5.23.2009 at 3:51 PM

anything with AJAX is going to be clean

#5 PhD Psychology

Posted By: PhD Psychology | 8.29.2009 at 12:10 AM

AJAX in there to make the experience even quicker and easier for our visitors, programming required a lot of experience and knowledge to develop a project,

#6 Master Degree

Posted By: Master Degree | 8.29.2009 at 12:11 AM

We can also do the same for the vote button, but we will add a little validation to this one.

#7 Online Computer Science degree

Posted By: Online Computer Science degree | 8.29.2009 at 12:11 AM

The reading of the results is a little more complex than adding.

#8 Associate degrees

Posted By: Associate degrees | 8.29.2009 at 12:11 AM

This is a good way of accessing all the events of a control.

#9 Education degree

Posted By: Education degree | 8.29.2009 at 12:12 AM

We are almost done with building the ASPX page.

#10 Tiffany Rings

Posted By: Tiffany Rings | 10.23.2009 at 7:37 AM

i like

#11 Make Money Online

Posted By: Make Money Online | 10.25.2009 at 8:56 PM

Great overview. Your style of writing is really a joy to read. <a href="http://www.mooladays.com">Make Money Online</a> <a href="http://www.hostdays.com">Web Hosting Reviews</a> <a href="http://www.hostdays.com/hosting-coupons/coupons">Hosting Coupons</a>

#12 free online games

Posted By: free online games | 11.24.2009 at 10:55 PM

AJAX in there to make the experience even quicker and easier for our visitors, programming required a lot of experience and knowledge to develop a project,

#13 club penguin cheats

Posted By: club penguin cheats | 12.11.2009 at 2:45 AM

We can also do the same for the vote button, but we will add a little validation to this one.

#14 echecks

Posted By: echecks | 12.11.2009 at 6:52 AM

Awesome article! Very useful for many working professionals as well as students working on various projects.

#15 work at home jobs

Posted By: work at home jobs | 12.12.2009 at 9:11 AM

Thank you for information nice topic, I think you have work hard for write this article.

#16 handbags shop

Posted By: handbags shop | 12.26.2009 at 12:27 AM

i like

#17 chapel hill real estate

Posted By: chapel hill real estate | 1.02.2010 at 5:40 AM

This tutorial was very nicely compiled. Appreciate you sharing this with us. Thanks.

#18 Chartered Accountants in Mississauga

Posted By: Chartered Accountants in Mississauga | 1.05.2010 at 3:53 AM

I've already bookmark this article for all my future references. This will definitely help many users in more than one ways. :)

#19 reviewsgoldmine

Posted By: reviewsgoldmine | 1.09.2010 at 3:27 AM

AJAX i think makes the experience even quicker and easier for our visitors, given that programming requires a lot of experience to develop a project

#20 Ecommerce Web Development

Posted By: Ecommerce Web Development | 1.18.2010 at 11:49 AM

Anything with AJAX is going to be clean..

#21 how to get pregnant fast

Posted By: how to get pregnant fast | 2.05.2010 at 2:11 AM

This is an extremely powerful tool, as we are able to access the WCF Service almost instantaneously, without posting back a page or waiting several seconds

#22 king

Posted By: king | 2.15.2010 at 5:13 PM

I cannot wait to try and implement this code. It seems complex for me, but I will try.

#23 mukluks super furry shearling snow winter boots

Posted By: mukluks super furry shearling snow winter boots | 2.16.2010 at 3:03 AM

AJAX, yes I had not been updating myself in Avex...thanks for this i shall put my hand on this too.

<a href="http://buyshearlingboots.blogspot.com/2010/02/mukluks-super-furry-shearling-snow.html">mukluks super furry shearling snow winter boots</a>

<a href="http://buyshearlingboots.blogspot.com/2010/02/faux-shearling-boots-ugg-kids-classic.html">Faux shearling boots ugg kids classic</a>

<a href="http://buyshearlingboots.blogspot.com/2010/02/bearpaw-pasador-rabbit-fur-shearling.html">bearpaw pasador rabbit fur shearling boots</a>

#24 propecia

Posted By: propecia | 2.17.2010 at 3:01 PM

Stored Procedure

CREATE 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

#25 Video Marketing Services

Posted By: Video Marketing Services | 2.23.2010 at 6:42 AM

Valuable information and excellent design you got here! I would like to thank you for sharing your thoughts and time into the stuff you post!! Thumbs up

#26 coach handbag outlet

Posted By: coach handbag outlet | 2.26.2010 at 8:04 PM

You are sure to find one for every occasion.

#27 free game online

Posted By: free game online | 3.07.2010 at 3:42 AM

Great article.I've bookmarked it already. Sincerely, Valerie.

#28 artificial insemination

Posted By: artificial insemination | 3.09.2010 at 11:57 AM

Good post….thanks for sharing.. very useful for me i will bookmark this for my future needed. thanks for a great source.