In this article I will explain how to implement 5 Star rating using jQuery plugin, save the rating value rated by user to database and display the value of Average Rating (in decimal format) and the Total Rating from database using jQuery AJAX and WebMethods in ASP.Net.
 
 
Database
For this article I have created a custom database the script of which is attached in the sample zip. The database has the following table
jQuery AJAX Star Rating plugin with Average Rating Value in Decimal from database in 
ASP.Net
The Id column is an INTEGER column and also is set IDENTITY ON. While the Rating column is a SMALLINT column to store the rating values from range 1 – 5.
 
HTML Markup
The HTML Markup consists of 5 RadioButtons and an HTML SPAN. The jQuery Star Rating plugin will be applied to the 5 RadioButtons while the HTML SPAN is used to display the Average Rating (in decimals) and the Total Rating value.
<div>
    <input name="rating_star" type="radio" class="rating_star" value="1" />
    <input name="rating_star" type="radio" class="rating_star" value="2" />
    <input name="rating_star" type="radio" class="rating_star" value="3" />
    <input name="rating_star" type="radio" class="rating_star" value="4" />
    <input name="rating_star" type="radio" class="rating_star" value="5" />
</div>
<br />
<hr />
<span id="rating"></span>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Data
Imports System.Web.Services
Imports System.Configuration
Imports System.Data.SqlClient
 
 
WebMethod for saving the jQuery Star Rating Values to Database
The following WebMethod gets called by the jQuery Star Rating plugin when user clicks on the Star in order to provide his rating.
The method inserts the Rating value received in the database.
C#
[WebMethod]
public static void Rate(int rating)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO UserRatings VALUES(@Rating)"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@Rating", rating);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
}
 
VB.Net
<WebMethod()> _
Public Shared Sub Rate(rating As Integer)
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand("INSERT INTO UserRatings VALUES(@Rating)")
            Using sda As New SqlDataAdapter()
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("@Rating", rating)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Using
End Sub
 
 
WebMethod for fetching the jQuery Star Rating Average and Total Value from Database
The following WebMethod is used to get the value of Average Rating (in decimals) and the Total Rating from database.
The fetched values are wrapped inside a JSON string and sent back to the calling jQuery AJAX function.
C#
[WebMethod]
public static string GetRating()
{
    string sql = "SELECT ROUND(ISNULL(CAST(SUM(Rating) AS NUMERIC(5, 2)) / COUNT(Rating), 0), 1) Average";
    sql += ", COUNT(Rating) Total FROM UserRatings";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            string json = string.Empty;
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                sdr.Read();
                json += "[ {";
                json += string.Format("Average: {0}, Total: {1}", sdr["Average"], sdr["Total"]);
                json += "} ]";
                sdr.Close();
            }
            con.Close();
            return json;
        }
    }
}
 
VB.Net
<WebMethod()> _
Public Shared Function GetRating() As String
    Dim sql As String = "SELECT ROUND(ISNULL(CAST(SUM(Rating) AS NUMERIC(5, 2)) / COUNT(Rating), 0), 1) Average"
    sql += ", COUNT(Rating) Total FROM UserRatings"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(sql)
            cmd.CommandType = CommandType.Text
            cmd.Connection = con
            con.Open()
            Dim json As String = String.Empty
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                sdr.Read()
                json += "[ {"
                json += String.Format("Average: {0}, Total: {1}", sdr("Average"), sdr("Total"))
                json += "} ]"
                sdr.Close()
            End Using
            con.Close()
            Return json
        End Using
    End Using
End Function
 
 
jQuery AJAX Client Side implementation
First a call is made to the GetRating WebMethod that gets the value of Average Rating (in decimals) and the Total Rating and then based on the Average Rating value appropriate CheckBox is checked and the Average Rating (in decimals) and the Total Rating is displayed in an HTML SPAN.
Once all this is done, the jQuery Star Rating plugin is applied to the series of CheckBoxes. And inside the Callback event handler a jQuery AJAX call is made to the WebMethod Rate, so that when rating is provided it will be saved in database.
Note: You can read more about the plugin and its working at the support site.
 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src='http://jquery-star-rating-plugin.googlecode.com/svn/trunk/jquery.rating.js'
    type="text/javascript"></script>
<link rel="Stylesheet" href="http://jquery-star-rating-plugin.googlecode.com/svn/trunk/jquery.rating.css" />
<script type="text/javascript">
    $(function () {
        GetRatings();
    });
    function GetRatings() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetRating",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var result = eval(response.d)[0];
                if (result.Average > 0) {
                    $('.rating_star').eq(result.Average - 1).attr("checked", "checked");
                   $("#rating").html("Average Rating: " + result.Average + " Total Rating:" + result.Total);
                }
                ApplyPlugin();
            },
            failure: function (response) {
                alert('There was an error.');
            }
        });
    }
    function ApplyPlugin() {
        $('.rating_star').rating({
            callback: function (value, link) {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/Rate",
                    data: "{rating: " + value + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        GetRatings();
                        alert("Your rating has been saved.");
                    },
                    failure: function (response) {
                        alert('There was an error.');
                    }
                });
            }
        });
    }
</script>
 
Stars displaying Average Rating
jQuery AJAX Star Rating plugin with Average Rating Value in Decimal from database in 
ASP.Net
 
Stars displaying Current Rating
jQuery AJAX Star Rating plugin with Average Rating Value in Decimal from database in 
ASP.Net
 
Demo
 
Downloads