Real-Time Poll Vote Results Using SignalR 2, Web API 2, jQuery And HighCharts

output

Introduction

In my previous article, we’ve done setting up the core foundation of our Online Poll System app: starting from creating a database and the required tables from the scratch up to displaying the poll in real-time, using ASP.NET SignalR. If you haven’t gone through my previous article, you can read it here:

In this particular series, we will take a look at how to implement a real-time voting result by presenting it in a form of chart. We’ll be using SignalR 2, Web API 2, jQuery and HighCharts to implement it. Note, before you go down further; make sure that you have referred my previous article, so you will be able to connect the dots in the picture as we move along.

Let’s Get Started!

If you’re ready, let’s go ahead and start cracking!

Adding the VoteResultViewModel

The first thing, we need to do is to add a new ViewModel. To do that, right-click on “Models/ViewModels” folder and then select Add > Class. Name the class as “VoteResultViewModel” and then copy the code, given below:

  1. namespace ASPNETCoreSignalRDemo.Models.ViewModels  
  2. {  
  3.     public class VoteResultViewModel  
  4.     {  
  5.         public string Choice { get; set; }  
  6.         public int Vote { get; set; }  
  7.     }  
  8. }  
The code above is nothing but just a class that houses two properties. Notice, that we’re not adding all the properties, which are present in the PollOption model: as a general rule of the thumb, we’ll be keeping our ViewModel as lightweight as possible, defining only, what we need in the View/UI. These properties will be used in our View to display the vote results.

Modifying the IPollManager Interface

Now, we need to modify our IPollManager interface to add a few methods. Our code should now look like:

  1. using System.Collections.Generic;  
  2. using ASPNETCoreSignalRDemo.Models.ViewModels;  
  3.   
  4. namespace ASPNETCoreSignalRDemo.Models  
  5. {  
  6.     public interface IPollManager  
  7.     {  
  8.         bool AddPoll(AddPollViewModel pollModel);  
  9.         IEnumerable<PollDetailsViewModel> GetActivePoll();  
  10.         void UpdatePollOptionVotes(int pollOptionID);  
  11.         IEnumerable<VoteResultViewModel> GetPollVoteResults(int pollID);  
  12.     }  
  13. }  
From the code, given above, we basically added two main methods: The UpdatePollOptionVotes() method that takes a pollOptionID as the parameter and the GetPollVoteResults() method, which takes a pollID as the parameter, which returns an IEnumerable of VoteResultViewModel.

Modifying the PollManager Class

Since we’ve changed our interface, we also need to change our concrete class, which implements the interface. Basically, we are going to implement the newly added methods from our interface in the PollManager class. Now, go ahead and open the PollManager.cs file and add the code, given below:
  1. private int GetPollOptionVotes(int pollOptionID)  
  2. {  
  3.     return _db.PollOption  
  4.             .Where(o => o.PollOptionId.Equals(pollOptionID))  
  5.             .Select(o => o.Vote).FirstOrDefault();  
  6.   
  7. }  
  8.   
  9. public void UpdatePollOptionVotes(int pollOptionID)  
  10. {  
  11.     var option = _db.PollOption.Where(o => o.PollOptionId.Equals(pollOptionID));  
  12.     if (option.Any())  
  13.     {  
  14.         int currentVotes = GetPollOptionVotes(pollOptionID);  
  15.   
  16.         if (currentVotes == 0)  
  17.             currentVotes = 1;  
  18.         else  
  19.             currentVotes++;  
  20.   
  21.         PollOption PO = option.SingleOrDefault();  
  22.         PO.Vote = currentVotes;  
  23.         _db.SaveChanges();  
  24.     }  
  25. }  
  26.   
  27. public IEnumerable<VoteResultViewModel> GetPollVoteResults(int pollID = 0)  
  28. {  
  29.     if (pollID == 0)  
  30.     {  
  31.         var poll = _db.Poll.Where(o => o.Active.Equals(true));  
  32.         if (poll.Any())  
  33.             pollID = poll.FirstOrDefault().PollId;  
  34.     }  
  35.   
  36.     var pollOption = _db.PollOption.Where(o => o.PollId.Equals(pollID));  
  37.     if (pollOption.Any())  
  38.     {  
  39.         return pollOption.Select(o => new VoteResultViewModel  
  40.         {  
  41.             Choice = o.Answers,  
  42.             Vote = o.Vote  
  43.         });  
  44.     }  
  45.     return Enumerable.Empty<VoteResultViewModel>();  
  46. }  
We’ve added three (3) main methods: a private GetPollOptionVotes() method and the public methods, which we need to implement from our interface. Let’s see, what we did in each method:

The GetPollOptionVotes() method takes a pollOptionID as the parameter. This method uses LINQ syntax to get the corresponding vote value from the database, based on the pollOptionID.

The UpdatePollOptionVotes() also takes a pollOptionID as the parameter. What it does is, it gets the particular PollOption record from the database, based on the pollOptionID. If the LINQ query returns any result, it will then get the current vote count by calling the GetPollOptionVotes() method. If the result is 0, the value for the current vote will be set to 1, else, it will increment the vote count to 1. It then updates the Vote value in the model and call _db.SaveChanges() to reflect the changes in the database.

The GetPollVoteResults() takes a pollID as an optional parameter. When a caller does not specify a parameter, it will get the pollID from the database by querying the Poll table, based on the Active flag. It then fetches the corresponding PollOption items and returns a new VoteResultViewModel, which contains Choice and Vote for the specific Poll.

Modifying the PollController API

Now, it’s time for us to create the required API methods to display the vote results. Open the API/PollController.cs file and add the following methods, given below:
  1. [HttpPost("{id}")]  
  2. public IActionResult AddVote(int id)  
  3. {  
  4.     _pollManager.UpdatePollOptionVotes(id);  
  5.     return new OkResult();  
  6. }  
  7.   
  8. [HttpGet("{id}")]  
  9. public IEnumerable<VoteResultViewModel> GetVoteResults(int id)  
  10. {  
  11.     return _pollManager.GetPollVoteResults(id).ToList();  
  12. }  
Both methods, given above were using an attribute based routing, as you can see with this attribute [HttpPost("{id}")] decorated in the method. The AddVote() method takes an ID(PollOptionID) as the parameter. This method will be invoked during POST request, via AJAX , once the user casts his vote. The GetVoteResults() takes an ID (PollID) as the parameter. As the method name suggests, this method gets the vote results from the database by calling the GetPollVoteResults() method, we defined in our PollManager class earlier.

Modifying the PollHub

We need to define a dedicated Hub method to display the results. Append the code, given below within PollHub Class:
  1. public void FetchVoteResult()  
  2. {  
  3.     IHubContext context = GlobalHost.ConnectionManager.GetHubContext<PollHub>();  
  4.     context.Clients.All.viewResults();  
  5. }  
A Hub is the center piece of the SignalR. Similar to the Controller in ASP.NET MVC, a Hub is responsible for receiving an input and generating the output to the client. This time, we will be invoking the FetchVoteResult() in the client-side – specifically, when a user submits his vote.

Modifying the Index View


It’s time for us to integrate the logic, when the users cast their votes. Here’s, how the updated Index.cshtml should look like:
  1. <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>  
  2. <script src="../Scripts/jquery.signalR-2.2.0.js"></script>  
  3. <script src="../signalr/hubs"></script>  
  4.   
  5. <script>  
  6.     var poll = $.connection.pollHub;  
  7.     $(function () {  
  8.         poll.client.displayPoll = function () {  
  9.             LoadActivePoll();  
  10.         };  
  11.   
  12.         $.connection.hub.start();  
  13.         LoadActivePoll();  
  14.   
  15.         $("#btnSubmit").on("click"function () {  
  16.             var selectedOption = $('input[name=poll]:checked''#tblPoll');  
  17.             if (selectedOption.val()) {  
  18.                 var row = $(selectedOption).closest('tr');  
  19.                 var choice = row.find("td:eq(0)").html().trim();  
  20.                 AddVote(choice);  
  21.             }  
  22.             else {  
  23.                 alert("Please take your vote.");  
  24.             }  
  25.         });  
  26.   
  27.         $("#lnkView").on("click"function () {  
  28.             this.href = this.href + '?pollID=' + $("#hidPollID").val();  
  29.         });  
  30.     });  
  31.   
  32.     function LoadActivePoll() {  
  33.         var $div = $("#divQuestion");  
  34.         var $tbl = $("#tblPoll");  
  35.         var $hid = $("#hidPollID");  
  36.         var $btn = $("#btnSubmit");  
  37.         $.ajax({  
  38.             url: '../api/poll',  
  39.             type: 'GET',  
  40.             datatype: 'json',  
  41.             success: function (data) {  
  42.                 if (data.length > 0) {  
  43.                     $btn.show();  
  44.                     $div.html('<h3>' + data[0].question + '</h3>');  
  45.                     $hid.val(data[0].pollID);  
  46.                     $tbl.empty();  
  47.                     var rows = [];  
  48.                     var poll = data[0].pollOption;  
  49.   
  50.                     $tbl.append('<tbody>');  
  51.                     for (var i = 0; i < poll.length; i++) {  
  52.                         rows.push('<tr>'  
  53.                                   +'<td style="display:none;">' + poll[i].pollOptionId + '</td>'  
  54.                                   +'<td>' + poll[i].answers + '</td>'  
  55.                                   +'<td><input name="poll" type="radio"/></td>'  
  56.                                   +'</tr>');  
  57.                     }  
  58.                     $tbl.append(rows.join(''));  
  59.                     $tbl.append('</tbody>');  
  60.                 }  
  61.             }  
  62.         });  
  63.     }  
  64.   
  65.     function AddVote(pollOptionID) {  
  66.         $.ajax({  
  67.             url: '../api/poll/AddVote',  
  68.             type: 'POST',  
  69.             datatype: 'json',  
  70.             data: { id: pollOptionID },  
  71.             success: function (data) {  
  72.                 poll.server.fetchVoteResult();  
  73.                 alert("Thank your for voting!");  
  74.             }  
  75.         });  
  76.   
  77.     }  
  78.   
  79. </script>  
  80.   
  81. <h2>ASP.NET Core Online Poll System with SignalR 2</h2>  
  82. <div id="divQuestion"></div>  
  83. <table id="tblPoll"></table>  
  84. <button type="button" id="btnSubmit" style="display:none">Vote</button>  
  85. <input type="hidden" id="hidPollID" />  
  86. @Html.ActionLink("View Results""Result""Home",null,new {  @id="lnkView"})  
We’ve done a lot of modifications there. Let’s see, what we just did:

Let’s start with the HTML. We’ve added 3 elements: a Button element, a Hidden element and an ActionLink. The Button allows the users to submit their votes. Hidden element will serve as the data storage for the PollID. The PollID value will be passed though the Result page, via querystring. The Action link will be used to redirect the users to the Result View. Notice, it follows the MVC convention – passing the Result as the Action name and Home as the Controller name. We also added HTML attribute to it, so we can set an ID for our ActionLink. We need that ID, so we can hook a “click” event to it for passing a querystring value before routing to the Results View.

Note: Getting and storing the PollID value isn’t really required, since we are only displaying one active poll at the time. In other words, we can just query the data by selecting the Poll, whose Active flag is True. We’re doing this, so you’ll have an idea of how to pass a value from one View to another in the context of ASP.NET MVC. Please be aware that there are many ways to pass the values between Views and what you will see in this article is just one of them.

jQuery $("#btnSubmit") click event will be invoked, once you cast a vote by clicking the button. It basically gets the selected item from the Radio Button input element. It then gets the corresponding PollOptionID for the item selected, using jQuery and pass the value to the AddVote() method. We also added a very basic validation to an alert message, if the user doesn’t select anything from the list.

The $("#lnkView") click event is, where we attached the PollID value, stored in a HiddenField input element as a query string value. This event will be invoked, when a user clicks on the “View Results” link.

The AddVote() function takes a PollOptionID as the parameter. This function is where, we issue an AJAX POST request to record the vote in our database. Notice the call to poll.server.fetchVoteResult(); - This line invokes the Hub and all the connected clients, who subscribe to it will get the updates.

What we changed inside the LoadActivePoll() function are:

 

  • Storing the PollID value in the Hidden element.
  • Showing the Button element if there’s any Poll data.
  • Appending the PollOptionID value upon generating HTML.

 

Modifying the HomeController Class

We need to add a new action method in our HomeController to return the Result View. Now, append the code, given below, within the aforementioned controller:

  1. public IActionResult Result(int pollID = 0)  
  2. {  
  3.     ViewBag.PollID = pollID;  
  4.     return View();  
  5. }  
The action method, given above, takes a PollID as an an optional parameter. The QueryString value, we passed earlier will be stored in the parameter pollID – ASP.NET MVC is smart enough to figure out without extra manipulation on our side. We can see, we store the value of PollID in a ViewBag, so we can reference the value in the Result View, which we will be creating it soon enough.

Adding the Result View and HighCharts Integration

Right click on the Views/Home folder and select Add > New Item. From the dialog, select “MVC View Page”, as shown in the figure, given below:

Result

We will name the view as “Result.cshtml”. Now, click Add to generate the file and replace everything in it with the following:
  1. <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>  
  2. <script src="../Scripts/jquery.signalR-2.2.0.js"></script>  
  3. <script src="../signalr/hubs"></script>  
  4. <script src="http://code.highcharts.com/highcharts.js"></script>  
  5.   
  6.   
  7. <script>  
  8.     var poll = $.connection.pollHub;  
  9.     $(function () {  
  10.         poll.client.viewResults = function () {  
  11.             LoadResults(0);  
  12.         };  
  13.   
  14.         $.connection.hub.start();  
  15.   
  16.         var pollID = @ViewBag.PollID;  
  17.         LoadResults(pollID);         
  18.     });  
  19.   
  20.     function LoadResults(pollID) {  
  21.         var $chart = $("#container");  
  22.   
  23.         $.ajax({  
  24.             url: '../api/poll/GetVoteResults',  
  25.             type: 'GET',  
  26.             datatype: 'json',  
  27.             data: { id: pollID },  
  28.             success: function (data) {  
  29.                 if (data.length > 0) {  
  30.                     var choices = [];  
  31.                     var votes = [];  
  32.                      
  33.                     for (var i = 0; i < data.length; i++) {  
  34.                         choices.push(data[i].choice);  
  35.                         votes.push(data[i].vote);  
  36.                          
  37.                     }  
  38.   
  39.                     $('#container').highcharts({  
  40.                         chart: {  
  41.                             type: 'bar'  
  42.                         },  
  43.                         title: {  
  44.                             text: 'Poll Vote Results'  
  45.                         },  
  46.                         xAxis: {  
  47.                             categories: choices  
  48.                         },  
  49.                         yAxis: {  
  50.                             title: {  
  51.                                 text: 'Best DOTA Heroes'  
  52.                             }  
  53.                         },  
  54.                         series: [{  
  55.                             name: 'Votes',  
  56.                             data: votes  
  57.                         }]  
  58.                     });  
  59.                 }  
  60.             }  
  61.         });  
  62.     }  
  63. </script>  
  64.   
  65. <div id="container" style="min-width: 310px; max-width: 600px; height: 400px; margin: 0 auto"></div>  
Let’s see what we did there.

Just like in our Index View, we're going to use jQuery CDN to reference the jQuery library. Take note of the sequence for adding the Scripts references. jQuery should be added first, then the SignalR Core JavaScript and SignalR Hubs script. Finally, we referenced HighCharts scripts, via code.highcharts.com. Keep in mind, you can also use NPM or Bower to manage the client-side resources such as HighCharts, jQuery and other client-side libraries.

For this particular demo, we are going to use HighCharts to display the charts in our page. I tend to use HiighCharts, because it provides sleek and fancy charts, which we can easily integrate in your app. Adding to that, it provides a variety to the chart types, which you can choose, down from simple to the complex type of charts. For more information, you can visit the official website at: http://www.highcharts.com/

Okay, let’s keep rolling.

At the very first line, within our <script> tag, we declared a connection to our PollHub. The code within jQuery document ready function ($(function () {});) is where we created a function delegate for subscribing to our PollHub. By subscribing to the Hub, ASP.NET SignalR will do all the complex plumbing for us to implement the real-time updates without any extra work needed in our side. When the a user cast a vote, the poll.client.viewResults() function delegate will be invoked and automatically fetches the data from our database by calling the LoadResult() function. We passed a 0 value in the LoadResult() as our Server-side code will take care of getting the PollID, based on the Active flag – see the GetPollVoteResults() method in the PollManager class. The other call to LoadResult() will be triggered, when a user clicks on the “View Results” link from the Index View. Remember, we setup a custom click event to pass the PollID as a QueryString value and then store PollID value in a ViewBag for this purpose.

The LoadResults() function is where, we issue an AJAX GET request to get the data, based on the PollID. If the request returns any data, it creates an array of choices and votes, based on JSON result. We then constructed a simple bar chart and fed the arrays of the data to the corresponding X and Y axis of the chart: The array of choices is our X-axis and the array of votes is our Y-axis. The chart will be drawn in the div element with an ID of “container”, as you can see from the code, given above.

Final Output

Here’s, the sample output for this demo:

Output

Notice, the chart changes after a user casted a vote. We can also see, how interactive HighCharts is.

Limitations

So far, we’ve done building a simple Real-Time Polling System. Please be aware, that this is just the basic implementation on how to create a poll and how to display the vote results in the real-time. The series of articles doesn’t cover voting validation for the users. You may need to use cookie or something similar to restrict the users to cast the multiple votes. Handling different types of Poll is not covered too and finally the Poll management isn’t complete. It lacks the ability to modify a Poll, to de-active a Poll and delete an existing Poll. Those were some of the limitations for this series.

Summary

In this, we’ve learned the basic implementation on how to display a poll vote results in the real-time, using the power of ASP.NET SignalR. We’ve learned, how to use jQuery and jQuery AJAX to communicate with our Web API methods. We have also learned how to create a simple dynamic chart in HighCharts. Despite the limitations mentioned, I hope you still find this article useful.

You can download the source at the top or at my Github repo

Up Next
    Ebook Download
    View all
    Learn
    View all