In this article I will explain with an example, how to implement
jQuery Star Rating plugin with average rating value in decimal from
SQL Server database in ASP.Net MVC.
This article will also illustrate how to calculate, Average and Total rating and display it using the
jQuery 5 Star Rating plugin.
jQuery Star Rating plugin
Please refer the following link for documentation for the
jQuery Star Rating plugin
Database
I have made use of the following table UserRatings with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling jQuery AJAX operations
GetRating
Inside this Action method, the Average ratings and the Total rating is calculated and fetched from database table.
The SQL Query is executed and the records are fetched using ExecuteReader method.
Finally, a JSON string is created consisting of Average ratings and the Total rating and it is returned to the View.
Rate
Inside this Action method, the rating given by user is inserted into the UserRatings table using ExecuteNonQuery method.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult 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, 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(json);
}
}
}
[HttpPost]
public ActionResult Rate(int rating)
{
string sql = "INSERT INTO UserRatings VALUES(@Rating)";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@Rating", rating);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
return new EmptyResult();
}
}
View
HTML Markup
The View consists of following elements:
div – For displaying the
jQuery Star Rating.
span – For displaying Average rating and Total rating.
jQuery Star Rating plugin Implementation
Inside the HTML Markup, the following CSS file is inherited.
1. star-rating-svg.min.css
And then, the following JS files are inherited.
1. jquery.min.js
2. jquery.star-rating-svg.min.js
Inside the
jQuery document ready event handler, the
GetRatings function is called.
GetRatings
Inside the
GetRatings method, an
AJAX call is made to the
GetRating Action Method.
Note: The
GetRating Action Method is used to get the ratings saved in the
SQL Server database table (discussed earlier).
The data received from the server is processed inside the
jQuery AJAX call
Success event handler and
jQuery Star Rating plugin is applied to the HTML DIV.
And the following properties of
jQuery Star rating plugin are set:
Properties:
initialRating – To set the initial rating value.
Note: Here it will be set based on the value returned from the GetRating Action Method.
starSize – It defines the size of each star.
useFullStars – It allows the stars to be displayed in full size.
When a star is clicked or rating is given, the callback function is executed which handled the submission of rating.
Inside the
callback function, another
AJAX call is made to the
Rate ActionMethod.
Note: The
Rate Action Method is used to save the ratings given by user in the
SQL Server database table (discussed earlier).
Then, based on the response, an appropriate message is displayed using
JavaScript Alert message Box.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<div class="rating_star">div>
<hr/>
<span id="rating"></span>
<link href="https://cdn.jsdelivr.net/npm/star-rating-svg@3.5.0/src/css/star-rating-svg.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/star-rating-svg@3.5.0/dist/jquery.star-rating-svg.min.js"></script>
<script type="text/javascript">
$(function () {
GetRatings();
});
function GetRatings() {
$.ajax({
type: "POST",
url: "/Home/GetRating",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var result = eval(response)[0];
if (result.Average > 0) {
$(".rating_star").starRating({
initialRating: result.Average,
starSize: 25,
useFullStars: true,
callback: function (value, $el) {
$.ajax({
type: "POST",
url: "/Home/Rate",
data: { "rating": value },
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("Your rating has been saved.");
},
failure: function (response) {
alert('There was an error.');
}
});
}
});
$("#rating").html("Average Rating: " + result.Average + " Total Rating:" + result.Total);
}
},
error: function (response) {
alert('There was an error.');
}
});
}
</script>
</body>
</html>
Screenshot
Demo
Downloads