Implement Bootstrap Star Rating using AngularJS and WebService in ASP.Net

Last Reply one month ago By dharmendr

Posted one month ago

How to implement bootstrap star rating with database record in angularjs in asp.net webservice

Posted one month ago Modified on one month ago

Hi rani,

Using angular ui.bootstrap.rating i have created the example.

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

Database

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

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
    <script type="text/javascript" src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
    <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script type="text/javascript">
        var app = angular.module('MyApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
        app.controller('MyController', function ($scope, $http) {
            GetRatings($scope, $http);
            $scope.rate = 0;
            $scope.total = 0;
            $scope.max = 10;
            $scope.hoveringOver = function (value) {
                $scope.overStar = value;
                $scope.percent = 100 * (value / $scope.max);
            };
            $scope.saveRate = function () {
                Rate($scope, $http, $scope.rate)
            };
        });
        function GetRatings($scope, $http) {
            $http.post("WebService.asmx/GetRating", { headers: { 'Content-Type': 'application/json'} })
            .then(function (response) {
                var result = eval(response.data.d)[0];
                $scope.rate = result.Average;
                $scope.total = result.Total;
            });
        }
        function Rate($scope, $http, value) {
            $http.post("WebService.asmx/Rate", { rating: value }, { headers: { 'Content-Type': 'application/json'} })
            .then(function (response) {
                GetRatings($scope, $http);
            });
        }
    </script>
</head>
<body>
    <div ng-app="MyApp" ng-controller="MyController">
        <span uib-rating ng-model="rate" max="max" on-hover="hoveringOver(value)" on-leave="overStar = null"
            ng-click="saveRate()" aria-labelledby="default-rating"></span>
        <span ng-class="{'label-warning': percent<30, 'label-info': percent>=30 && percent<70, 'label-success': percent>=70}" 
            class="label" ng-show="overStar" >{{percent}}%</span>
        <br />
        Average Rating: {{rate}}
        <br />
        Total Rating: {{total}}
    </div>
</body>
</html>

WebService

C#

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

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public 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 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

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

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
    Inherits System.Web.Services.WebService
    <WebMethod()>
    Public 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 Sub Rate(ByVal rating As Integer)
        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
End Class

Screenshot

For more details on angular ui.bootstrap.rating refer below link. 

http://angular-ui.github.io/bootstrap/