AJAX Rating in ASP.NET 2.0


By arun thakur
Printer Friendly Version
  

This is a rating bar script done with asp.net and sql server that allows users to rate things like can be done on Netflix or Amazon, all web 2.0-like with no page refresh, so you should be able to adapt it to your situation without too much trouble.



This article describes an ASP.NET web module along with some chunks of Javascripts and ...Ajax to create a Rating System. This can be added /customized for any table to add a rating/score module. I was quite amazed, when i first saw the capability of rating multiple items at amazon website without refreshing the page. That nice piece of functionality followed me like destiny, till i needed to implement it in a web application.

Well ! putting it in a live scenario needs much more than just javascript. I started with a bit of frenzied hacking. To understand how exactly it works, by scanning the javascript from online asynchronous rating websites. That was just the beginning, on the way i learned much more than earlier imagined.  Here is the result of the effort. 

The target was to create a cross browser rating/score system like amazon or better:

  1. Rating: User should be able to Rate a record (1-5)
  2. Accuracy: Number of votes and total score should be accurate and saved and should not be lost in calculations
  3. Real time: Rate/score should be displayed after rating instantly 
  4. Reusable: It should be easily plugged into any table for reusability
  5. Avoiding multiple ratings: Basic mechanism to avoid multiple ratings by the same user
  6. Best approach: Compare the pros and cons for both Amazon and Ajax approach
  7. Security: Few words\\

Those were the initial thoughts, but to make it a general reusable and extensible module, I made some assumptions:

  • The table which will have the records to be rated will have a Primary Key ID (integer and identity) and the it will be the first field in the table.
  • The Table will have atleast two Fields: RatedBy  & Score
  • For the current example to work you will need atleast one extra field Title

Data access class


There is a standard data access class, clsDataAccess.cs, which handles all the data related actions.

Code: I have kept here only the names of the functions, just to give you a glimpse of the data access methods.




using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Rating;

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


            if ((Convert.ToInt32(Request.QueryString["Rating"]) == 1) || (Convert.ToInt32(Request.QueryString["Rating"]) == 2) || (Convert.ToInt32(Request.QueryString["Rating"]) == 3) || (Convert.ToInt32(Request.QueryString["Rating"]) == 4) || (Convert.ToInt32(Request.QueryString["Rating"]) == 5))
            {
                Label1.Text = "<IMG src='images/" + Request.QueryString["rating"] + "star.gif'>";
                Label2.Text = "<IMG src='images/saved.gif'>";
            }
            else
            {
                Response.Redirect("Rate.aspx?id=" + Convert.ToInt32(Request.QueryString["id"]));
            }



            string p = "Select * from TEST_TABLE1 WHERE id = '1'";

            clsDataAccess myDAR = new clsDataAccess();
            myDAR.openConnection();
            double myRatedBy = Convert.ToInt32(myDAR.getValue(p, Convert.ToInt32(ConfigurationSettings.AppSettings["RatedByField"])));
            double myScore = Convert.ToDouble(myDAR.getValue(p, Convert.ToInt32(ConfigurationSettings.AppSettings["ScoreField"])));


            double myCRating = Convert.ToDouble(Request.QueryString["Rating"]);

            double myTotalRating = 0.0;

            if ((Convert.ToInt32(Request.QueryString["Rating"]) == 1) || (Convert.ToInt32(Request.QueryString["Rating"]) == 2) || (Convert.ToInt32(Request.QueryString["Rating"]) == 3) || (Convert.ToInt32(Request.QueryString["Rating"]) == 4) || (Convert.ToInt32(Request.QueryString["Rating"]) == 5))
                myTotalRating = (myScore + myCRating) / (myRatedBy + 1);
            else
                myTotalRating = (myScore) / (myRatedBy);

            myDAR.closeConnection();

            string myTotalRatingString = "";

            if ((myTotalRating < 1) && (myTotalRating > 0))
                myTotalRatingString = ".5";
            else if (myTotalRating == 1.0)
                myTotalRatingString = "1";
            else if ((myTotalRating > 1) && (myTotalRating < 2))
                myTotalRatingString = "1.5";
            else if (myTotalRating == 2.0)
                myTotalRatingString = "2";
            else if ((myTotalRating > 2) && (myTotalRating < 3))
                myTotalRatingString = "2.5";
            else if (myTotalRating == 3.0)
                myTotalRatingString = "3";
            else if ((myTotalRating > 3) && (myTotalRating < 4))
                myTotalRatingString = "3.5";
            else if (myTotalRating == 4.0)
                myTotalRatingString = "4";
            else if ((myTotalRating > 4) && (myTotalRating < 5))
                myTotalRatingString = "4.5";
            else if (myTotalRating == 5.0)
                myTotalRatingString = "5";



            Label3.Text = "<IMG src='images/stars" + myTotalRatingString + ".gif'>";

            int RatedBy = 0;
            int TRating = 0;
            if ((Convert.ToInt32(Request.QueryString["Rating"]) == 1) || (Convert.ToInt32(Request.QueryString["Rating"]) == 2) || (Convert.ToInt32(Request.QueryString["Rating"]) == 3) || (Convert.ToInt32(Request.QueryString["Rating"]) == 4) || (Convert.ToInt32(Request.QueryString["Rating"]) == 5))
            {
                RatedBy = Convert.ToInt32(myRatedBy) + 1;
                TRating = Convert.ToInt32(myScore) + Convert.ToInt32(Request.QueryString["rating"]);
            }
            else
            {
                RatedBy = Convert.ToInt32(myRatedBy);
                TRating = Convert.ToInt32(myScore);
            }

            string q = "UPDATE TEST_TABLE  SET Score = '" + TRating + " ' , RatedBy = '" + RatedBy + "' WHERE id = '1'";

            clsDataAccess myDA = new clsDataAccess();
            myDA.openConnection();
            myDA.saveData(q);
            myDA.closeConnection();

            if ((Convert.ToInt32(Request.QueryString["Rating"]) == 1) || (Convert.ToInt32(Request.QueryString["Rating"]) == 2) || (Convert.ToInt32(Request.QueryString["Rating"]) == 3) || (Convert.ToInt32(Request.QueryString["Rating"]) == 4) || (Convert.ToInt32(Request.QueryString["Rating"]) == 5))
            {
                Response.Cookies["RatedAmz" + Convert.ToInt32(Request.QueryString["id"])].Value = Request.QueryString["Rating"].ToString();
            }


        }
    }
}



 For this we need set of five images for the stars and five for the comments as shown above and two javascript function DisplayStars and DisplayMsg to display those images on mouseover.




function StarMouseOut(id){
    starTwinkler[id] = window.setTimeout("SwapStars('"+id+"')", delayTime);
    msgTwinkler[id] = window.setTimeout("SwapStarMsg('"+id+"')", delayTime);
}
function DisplayStars (id, rating){
    var starID = "stars." + id;
    starTwinkler[id] = 0;
    msgTwinkler[id] = 0;
    document.write("<map name='starmap" + id +"'>");
    var i = 0;
    for (i = 1; i < 6; i++) {
    document.write("<area shape=rect " +
    "coords='" + starMap[i] + "' " +
    "onMouseOver=\"StarMouseOver('" + id + "'," + i + ");\" " +
    "onMouseOut=\"StarMouseOut('" + id + "');\" " +
    "onClick=\"SaveStars('" + id + "'," + i + ");" +
    "\" >");
    }
    document.write("</map>");
    document.write("<img vspace=2 title = 'Rate Picture' src='" + starImages[rating] + "'");
    document.write(" border=0 usemap='#starmap" + id);
    document.write("' id='" + starID + "'>");
}


* By Amazon Way i meant it can simulate the rating system like the amazon website, it does not claims that this is the way amazon is doing there rating.




button
 
Article Discussion: ajax Rating in asp.net 2.0
  arun thakur posted at 14-Aug-07 08:37
Original Article

 
  savestars
  matt p replied to arun thakur at 29-Apr-08 06:05
javascript refers to "SaveStars", but can't find that function in the article..??
   

 
  requred code
  arun thakur replied to matt p at 30-Apr-08 12:01
if you still requred code  i can proved to you ?

 
  re: Stars
  matt p replied to arun thakur at 30-Apr-08 10:10
don't understand what you mean.. i was just trying to find the SaveStars function..so I would know how to implement the code.. :)  maybe it's all in a DLL or something

 
  code for rating
  vamshi bethi replied to arun thakur at 10-Jun-08 02:48
can anyone please provide the code for rating