Thursday, May 2, 2013

Ajax Rating control sample in ASP.NET


In this post am gonna provide a simple Ajax rating control sample. When u change the rating by clicking the Star, the value will be displayed in a Label control. It will be useful when you develop a shopping cart kind of application. I have also attached the star images necessary for this sample.
Design Code:
  1. <cc:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
  2. </cc:ToolkitScriptManager>
  3.  
  4. <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  5. <ContentTemplate>
  6. <cc:Rating ID="Rating1" runat="server" MaxRating="5" CurrentRating="1" CssClass="ratingStar" StarCssClass="ratingItem" EmptyStarCssClass="Empty" AutoPostBack="True" OnChanged="Rating1_Changed1">
  7. </cc:Rating>
  8. </ContentTemplate>
  9. </asp:UpdatePanel>
  10.  
  11. <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

C# Code:
  1. const int RATING1_MINIMUM = 1;
  2. const int RATING1_MAXIMUM = 5;
  3. protected void Page_Load(object sender, EventArgs e)
  4. {
  5. if (!IsPostBack)
  6. {
  7. Evaluate_Rating1(Rating1.CurrentRating);
  8. }
  9. }
  10. public void Evaluate_Rating1(int value)
  11. {
  12. Label1.Text = EvaluateRating(value, Rating1.MaxRating, RATING1_MINIMUM, RATING1_MAXIMUM);
  13. }
  14.  
  15. public static string EvaluateRating(int value, int maximalValue, int minimumRange, int maximumRange)
  16. {
  17. int stepDelta = (minimumRange == 0) ? 1 : 0;
  18. double delta = (double)(maximumRange - minimumRange) / (maximalValue - 1);
  19. double result = delta * value - delta * stepDelta;
  20. return FormatResult(result);
  21. }
  22.  
  23. public static string FormatResult(double value)
  24. {
  25. return String.Format("{0:g}", value);
  26. }
  27. protected void Rating1_Changed1(object sender, AjaxControlToolkit.RatingEventArgs e)
  28. {
  29. Evaluate_Rating1(int.Parse(e.Value));
  30. }

CSS Code:
  1. .ratingStar
  2. {
  3. white-space:nowrap;
  4. margin:1em;
  5. height:14px;
  6. }
  7. .ratingStar .ratingItem
  8. {
  9. font-size: 0pt;
  10. width: 13px;
  11. height: 12px;
  12. margin: 0px;
  13. padding: 0px;
  14. display: block;
  15. background-repeat: no-repeat;
  16. cursor:pointer;
  17. }
  18.  
  19. .ratingStar .Filled
  20. {
  21. background-image: url(../images/ratingStarFilled.png);
  22. }
  23.  
  24. .ratingStar .Empty
  25. {
  26. background-image: url(../images/ratingStarEmpty.png);
  27. }
  28.  
  29. .ratingStar .Saved
  30. {
  31. background-image: url(../images/ratingStarSaved.png);
  32. }

Images:



2 comments:

  1. Hi there, its pleasant article regwrding media print, we all
    be aware of media is a impressive source of data.

    ReplyDelete
  2. These are inn fact wonderful ideas in regarding blogging.
    You have touched some good points here. Anyy way keep up
    wrinting.

    ReplyDelete