DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core

Trending

  • Testing SingleStore's MCP Server
  • Debugging With Confidence in the Age of Observability-First Systems
  • How to Format Articles for DZone
  • Building Resilient Networks: Limiting the Risk and Scope of Cyber Attacks
  1. DZone
  2. Coding
  3. Frameworks
  4. Building a Star Rating System with ASP.NET MVC and jQuery

Building a Star Rating System with ASP.NET MVC and jQuery

While working on the WeBlog project I realized that I needed a star rating system for blog posts.

By 
Michael Ceranski user avatar
Michael Ceranski
·
Mar. 02, 10 · News
Likes (0)
Comment
Save
Tweet
Share
32.4K Views

Join the DZone community and get the full member experience.

Join For Free

While working on the WeBlog project I realized that I needed a star rating system for blog posts. A star rating allows your readings to rate content based on a 0-5 scale.

A fully lit star represents a full point on the rating scale. Therefore in order to give half point increments each star uses two images. 

Left off: star-left-off Left on: star-left-on Right off: star-right-off Right on: star-right-on

When you put a left and a right image together it forms a complete star. So If you have a rating a 3.5 you would have the following stars displayed: Star #1 left on, right on #2 left on, right on #3 left on, right on #4 left on, right off #5 left off, right off.

Displaying the Current Rating

In MVC, the logic to determine which stars (images) should be initially displayed is best accomplished with a HTML helper:

public static  string Ratings(this HtmlHelper helper, PostModel post) {    StringBuilder sb = new StringBuilder();    sb.AppendFormat("<span class='rating' rating='{0}' post='{1}' title='Click to cast vote'>", post.Rating, post.ID);    string formatStr = "<img src='/Content/images/{0}' alt='star' width='5' height='12' class='star' value='{1}' />";     for (Double i = .5; i <= 5.0; i = i + .5) {        if (i <= post.Rating) {            sb.AppendFormat(formatStr, (i * 2) % 2 == 1 ? "star-left-on.gif" : "star-right-on.gif", i);        }        else {            sb.AppendFormat(formatStr, (i * 2) % 2 == 1 ? "star-left-off.gif" : "star-right-off.gif", i);        }    }    sb.AppendFormat(" <span>Currently rated {0} by {1} people</span>", post.Rating, post.Raters);    sb.Append("</span>");    return sb.ToString();}

This helper method builds the images based on the post's current rating. The loop, which creates the images, steps in half point increments. If the counter variable is less than or equal to the post rating then a "turned on" image is displayed. There is also logic in the loop to determine if a right or left image is displayed based on the current counter value. Once, the helper method is in place you can display the rating control with the following line of code :

<%=Html.Ratings( Model ) %>

User Rating Mode

When a user hovers over the stars, the control goes into "user rating mode". Instead of the stars showing the average rating it will now show the rating that the user is trying to apply to the post. So if I hover over the first half of the third star, all the images up to that point will show as turned on, and the remaining images will be turned off. In order to toggle the images on and off I used jQuery.

The following code is fired whenever a user puts their mouse over an element which uses the class name "star". All the images in the star rating control use are utilizing the “star” class. Each image element also has an attribute "value" which contains the rating for that particular element. For example the first half star has a value of .5, the second star has a value of 1 and so on and so forth. The images are then updated using the setRating function which we will discuss momentarily.

$(".star").mouseover(function () {    var span = $(this).parent("span");    var newRating = $(this).attr("value");    setRating(span, newRating);});

A similar function is used to re-draw the average rating when the user’s mouse is moved out of the control. Whenever a user leaves the control the average rating needs to be displayed again. The average rating value is stored in a rating attribute on the span that encapsulates all the images:

$(".star").mouseout(function () {    var span = $(this).parent("span");    var rating = span.attr("rating");    setRating(span, rating);});

Here is the setRating function. This function updates the images based on the rating value:

function setRating(span, rating) {    span.find('img').each(function () {        var value = parseFloat($(this).attr("value"));        var imgSrc = $(this).attr("src");        if (value <= rating)            $(this).attr("src", imgSrc.replace("-off.gif", "-on.gif"));        else            $(this).attr("src", imgSrc.replace("-on.gif", "-off.gif"));    });}

The final piece of jQuery code is used to handle the click event. The click event is responsible for casting the vote to the server:

$(".star").click(function () {    var span = $(this).parent("span");    var newRating = $(this).attr("value");    var postID = span.attr("post");    var text = span.children("span");    $.post("/Post/SetRating", { id: postID, rating: newRating },        function (obj) {            if (obj.Success) {                text.html("Currently rated " + obj.Result.Rating + " by " + obj.Result.Raters + " people"); //modify the text                span.attr("rating", obj.Result.Rating); //set the rating attribute                setRating(span, obj.Result.Rating); //update the display                alert("Thank you, your vote was casted successfully.");            }            else {                alert(obj.Message); //failure, show message            }        }    );});

This code is fired whenever you click on one of the stars. The Postcontroller has a method called SetRating  ("/Post/SetRating") which is called using jQuery's post method. This makes an asynchronous call to the server and saves the rating to the data store. When the results are returned from the server an object is returned which contains a Boolean flag (obj.Success) indicating the data was updated successfully, an optional message (obj.Message) which can display and errors caught in the controller and a Result (obj.Result) object which contains the updated value for the number of raters (obj.Result.Raters) and the average rating (obj.Result.Rating). Here is the code for the SetRating method:

public JsonResult SetRating(Guid id, double rating) {    try {        if (CanUserVote(id, rating) == false) {            return Json(new JsonResponse            {                Success = false,                Message = "Sorry, you already voted for this post"                        });        }        PostModel post = Engine.Posts.SetRating(id, rating);        return Json(new JsonResponse        {            Success = true,            Message = "Your Vote was cast successfully",            Result = new { Rating = post.Rating, Raters = post.Raters }        });    }    catch (Exception ex) {        return Json(new JsonResponse        {            Success = false,            Message = ex.Message                            });    }}

In the code above, there is a call to the method named CanUserVote. This code prevents users from voting multiple times on the same post by storing a cookie. Basically, all this method does is store an entry for each post in a cookie named "Votes". If the post is not in the cookie then it returns true, meaning you can vote. Otherwise it returns false.

private Boolean CanUserVote(Guid id, double rating) {    HttpCookie voteCookie = Request.Cookies["Votes"];    if (voteCookie != null) {        if (voteCookie[id.ToString()] != null) {            return false;        }    }    //create the cookie and set the value    voteCookie = new HttpCookie("Votes");    voteCookie[id.ToString()] = rating.ToString();    Response.Cookies.Add(voteCookie);    return true;}

Conclusion

Building a star rating system is a lot of fun. The algorithms are straightforward and jQuery makes the client side code easy to write. If you want to see the working demo then download the source from the WeBlog project. WeBlog is the open source blogging engine that I started a couple of months ago. WeBlog is written in MVC2 and NetFx 4 and relies on jQuery for the client side magic. You will need Visual Studio 2010 RC in order to compile it.

 

ASP.NET MVC JQuery ASP.NET

Published at DZone with permission of Michael Ceranski, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!