In this article I will explain with an example, how to implement jQuery 5 Star Rating plugin using Entity Framework 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.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 

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.
ASP.Net MVC: Implement Star Rating with Database
 
Note: You can download the database table SQL by clicking the download link below.         
          Download SQL file
 
 

Creating an Entity Data Model

The very first step is to create an ASP.Net MVC Application and connect it to the database using Entity Framework.
Note: For beginners in ASP.Net MVC and Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
 
Following is the Entity Data Model of the UserRatings Table.
ASP.Net MVC: 5 Star Rating using Entity Framework
 
 

Namespaces

You will need to import the following namespace.
using System.Linq;
 
 

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 UserRating Entity Data Model 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
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public JsonResult GetRating()
    {
        string json = string.Empty;
        using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
        {
            List<UserRating> ratings = entities.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 ActionResult Rate(short rating)
    {
        using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
        {
            entities.UserRatings.Add(new UserRating { Rating = rating });
            entities.SaveChanges();
        }
        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/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

ASP.Net MVC: 5 Star Rating using Entity Framework
 
 

Demo

 
 

Downloads