Sunday, August 11, 2019

How to Implement 5 star rating system in ASP.NET inside Gridview

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create 2 table for Save/ Fetch Data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used two tables as below
Table1


Table2

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >

Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Class.

Right Click on Solution Explorer > Add > Class > Enter Class Name > Add.
Here is the class. 
  1. namespace ASPRatingApp
  2. {
  3. public class ArticleWithScore
  4. {
  5. public int ArticleID { get; set; }
  6. public string ArticleTitle { get; set; }
  7. public int Score { get; set; }
  8. }
  9. }

Step-6: Add a Webpage and Design for show/save rating from/to database.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

JS Code 
  1. <script src="Scripts/jquery-1.7.1.js"></script>
  2. <script language="javascript" type="text/javascript">
  3. $(document).ready(function () {
  4. $(".rating-star-block .star").mouseleave(function () {
  5. $("#" + $(this).parent().attr('id') + " .star").each(function () {
  6. $(this).addClass("outline");
  7. $(this).removeClass("filled");
  8. });
  9. });
  10. $(".rating-star-block .star").mouseenter(function () {
  11. var hoverVal = $(this).attr('rating');
  12. $(this).prevUntil().addClass("filled");
  13. $(this).addClass("filled");
  14. $("#RAT").html(hoverVal);
  15. });
  16. $(".rating-star-block .star").click(function () {
  17. var v = $(this).attr('rating');
  18. var newScore = 0;
  19. var updateP = "#" + $(this).parent().attr('id') + ' .CurrentScore';
  20. var artID = $("#" + $(this).parent().attr('id') + ' .articleID').val();
  21. $("#" + $(this).parent().attr('id') + " .star").hide();
  22. $("#" + $(this).parent().attr('id') + " .yourScore").html("Your Score is : &nbsp;<b style='color:#ff9900; font-size:15px'>" + v + "</b>");
  23. $.ajax({
  24. type: "POST",
  25. url: "Default.aspx/SaveRating",
  26. data: "{articleID: '" + artID + "',rate: '" + v + "'}",
  27. contentType: "application/json; charset=utf-8",
  28. dataType: "json",
  29. success: function (data) {
  30. setNewScore(updateP, data.d);
  31. },
  32. error: function (data) {
  33. alert(data.d);
  34. }
  35. });
  36. });
  37. });
  38. function setNewScore(container, data) {
  39. $(container).html(data);
  40. $("#myElem").show('1000').delay(2000).queue(function (n) {
  41. $(this).hide(); n();
  42. });
  43. }
  44. </script>
HTML Code 
  1. <style type="text/css">
  2. .rating-star-block .star.outline {
  3. background: url("images/star-empty-lg.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
  4. }
  5. .rating-star-block .star.filled {
  6. background: url("images/star-fill-lg.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
  7. }
  8. .rating-star-block .star {
  9. color:rgba(0,0,0,0);
  10. display : inline-block;
  11. height:24px;
  12. overflow:hidden;
  13. text-indent:-999em;
  14. width:24px;
  15. }
  16. a {
  17. color:#005782;
  18. text-decoration:none;
  19. }
  20. </style>
  21. <h3>Rating in ASP.NET</h3>
  22. <div>
  23. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CellPadding="5">
  24. <Columns>
  25. <asp:BoundField HeaderText="Article ID" DataField="ArticleID" />
  26. <asp:BoundField HeaderText="Article Title" DataField="ArticleTitle" />
  27. <asp:TemplateField>
  28. <ItemTemplate>
  29. <div class="rating-star-block" id='div_<%#Container.DataItemIndex %>'>
  30. <input type="hidden" class="articleID" value='<%#Eval("ArticleID") %>' />
  31. Current Score :<span class="CurrentScore"><%#Eval("Score") %></span><br /><div class="yourScore">Your Score : </div>
  32. <a class="star outline" href="#" rating="1" title="vote 1"> vote 1</a>
  33. <a class="star outline" href="#" rating="2" title="vote 2"> vote 2</a>
  34. <a class="star outline" href="#" rating="3" title="vote 3"> vote 3</a>
  35. <a class="star outline" href="#" rating="4" title="vote 4"> vote 4</a>
  36. <a class="star outline" href="#" rating="5" title="vote 5"> vote 5</a>
  37. </div>
  38. </ItemTemplate>
  39. </asp:TemplateField>
  40. </Columns>
  41. </asp:GridView>
  42. <div id="myElem" style="position:absolute; top:10px; left:50%; display:none; background-color:yellow; padding:5px; border:1px solid red">
  43. Thank you for your rating!
  44. </div>
  45. </div>

Step-7: Write code in page_load event for fetch data from database and show in Gridview.


  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!IsPostBack)
  4. {
  5. PopulateArticle();
  6. }
  7. }
Here is the function

  1. private void PopulateArticle()
  2. {
  3. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  4. {
  5. var v = (from a in dc.Articles
  6. join b in dc.ArticleScores on a.ArticleID equals b.ArticleID into bb
  7. from b in bb.DefaultIfEmpty()
  8. group new { a, b } by new { a.ArticleID, a.ArticleTitle } into AA
  9. select new
  10. {
  11. AA.Key.ArticleID,
  12. AA.Key.ArticleTitle,
  13. Score = AA.Sum(a => a.b.Score) == null ? 0 : AA.Sum(a => a.b.Score),
  14. Count = AA.Count()
  15. });
  16. List<ArticleWithScore> AWS = new List<ArticleWithScore>();
  17. foreach (var i in v)
  18. {
  19. AWS.Add(new ArticleWithScore
  20. {
  21. ArticleID = i.ArticleID,
  22. ArticleTitle = i.ArticleTitle,
  23. Score = i.Score/i.Count
  24. });
  25. GridView1.DataSource = AWS;
  26. GridView1.DataBind();
  27. }
  28. }
  29. }

Step-8: Write code(function) for Save users rating into database which is calling from Jquery.

               Import this 2 Namespace 
  1. using System.Web.Services;
  2. using System.Web.Script.Services;

  1. [WebMethod]
  2. [ScriptMethod(ResponseFormat= ResponseFormat.Json)]
  3. public static int SaveRating(int articleID, int rate)
  4. {
  5. int result = 0;
  6. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  7. {
  8. dc.ArticleScores.Add(new ArticleScore
  9. {
  10. ArticleID = articleID,
  11. ScoreID = 0,
  12. Score = rate,
  13. CreateDate = DateTime.Now
  14. });
  15. dc.SaveChanges();
  16.  
  17. var newScore = (from a in dc.ArticleScores
  18. where a.ArticleID.Equals(articleID)
  19. group a by a.ArticleID into aa
  20. select new
  21. {
  22. Score = aa.Sum(a=>a.Score)/aa.Count()
  23. }).FirstOrDefault();
  24. result = newScore.Score;
  25. }
  26. return result;
  27. }

Step-9: Run Application

1 comment:

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...