Bootstrap Star Rating plugin with Average Rating Value from database using jQuery Ajax in ASP.Net

Last Reply 3 months ago By dharmendr

Posted 3 months ago

How to Create Rating Control in boostrap and how to save in database

You are viewing reply posted by: dharmendr 3 months ago.
Posted 3 months ago

Hi IamAzhar,

Check this example. Now please take its reference and correct your code.

Database

CREATE TABLE UserRatings
(
	Id INT PRIMARY KEY IDENTITY,
	Rating NUMERIC(5, 2)
)

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-star-rating/4.0.2/css/star-rating.min.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-star-rating/4.0.2/js/star-rating.min.js"></script>
    <script type="text/javascript">
        $(function () {
            GetRatings();
            $('.filled-stars').click(function () {
                var value = parseInt($(this)[0].style.width.replace('%')) / 20;
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/Rate",
                    data: "{rating: " + value + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert("Your rating has been saved.");
                        GetRatings();
                    },
                    failure: function (response) {
                        alert('There was an error.');
                    }
                });
            });
        });
        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) {
                        $('.filled-stars')[0].style.width = result.Average * 20 + "%";
                        $("#rating").html("Average Rating: " + result.Average + " Total Rating: " + result.Total);
                    }
                    else {
                        $('.filled-stars')[0].style.width = "0%";
                        $("#rating").html("Average Rating: 0 Total Rating: 0");
                    }
                },
                failure: function (response) {
                    alert('There was an error.');
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        <input id="rating_star" class="rating rating-loading" value="0" data-min="0" data-max="5"
            data-step="0.5" data-size="xs">
        <hr />
        <span id="rating"></span>
    </div>
    </form>
</body>
</html>

Namespace

C#

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

VB.Net

Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services

Code

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;
        }
    }
}

[WebMethod]
public static void Rate(decimal 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 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 SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = 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

<WebMethod()>
Public Shared Sub Rate(ByVal rating As Decimal)
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand("INSERT INTO UserRatings VALUES(@Rating)")
            Using sda As SqlDataAdapter = 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

Screenshot