In this article I will explain with an example, how to implement
jQuery 5 Star Rating plugin using
Entity Framework in ASP.Net Core 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.
Database Context
Once the
Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
using jQuery_Rating_EF_Core.Models;
using Microsoft.EntityFrameworkCore;
namespace jQuery_Rating_EF_Core
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<RatingModel> UserRatings { get; set; }
}
}
Model
The Model class consists of following properties.
public class RatingModel
{
public int Id { get; set; }
public short Rating { get; set; }
}
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, a Generic List collection of RatingModel class is created and records are fetched from the UserRatings table.
Then, the average of all ratings is calculated using Lambda expression and LINQ Average function.
Finally,a
JSON string is created consisting of Average rating 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
Entity Framework.
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult GetRating()
{
string json = string.Empty;
List<RatingModel> ratings = this.Context.UserRatings.ToList();
double average = ratings.Average(u => u.Rating);
json += "[ {";
json += string.Format("Average: {0}, Total: {1}", average.ToString("0.00"), ratings.Count());
json += "} ]";
return Json(json);
}
[HttpPost]
public IActionResult Rate(short rating)
{
this.Context.UserRatings.Add(new RatingModel { Rating = rating });
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 Action Method.
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/Rating",
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