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.
Join the DZone community and get the full member experience.
Join For FreeWhile 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: Left on: Right off: 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.
Published at DZone with permission of Michael Ceranski, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments