Wednesday 4 June 2014

Rating control in asp.net with database


Rating Control properties:
<ajaxToolkit:Rating ID="ThaiRating" runat="server"
    CurrentRating="2"
    MaxRating="5"
    StarCssClass="ratingStar"
    WaitingStarCssClass="savedRatingStar"
    FilledStarCssClass="filledRatingStar"
    EmptyStarCssClass="emptyRatingStar"
    OnChanged="ThaiRating_Changed" />

AutoPostBack - True to cause a postback on rating item click.
CurrentRating - Initial rating value
MaxRating - Maximum rating value
ReadOnly - Whether or not the rating can be changed
StarCssClass - CSS class for a visible star
WaitingStarCssClass - CSS class for a star in waiting mode
FilledStarCssClass - CSS class for star in filled mode
EmptyStarCssClass - CSS class for a star in empty mode
RatingAlign - Alignment of the stars (Vertical or Horizontal)
RatingDirection - Orientation of the stars (LeftToRightTopToBottom or RightToLeftBottomToTop)
OnChanged - ClientCallBack event to fire when the rating is changed
Tag - A custom parameter to pass to the ClientCallBack

First we have to create to create table. Sample table design given below

Table design (UserRating):
Column Name
Data Type
Id (Auto Increment)
int
Rating
Int

In we.config  file we have to set connection string
Sample code: 
<connectionStrings>
        <add name="ConnectionString" connectionString="Data Source=localhost;                           
                                        Initial Catalog=Demo; Integrated Security=True"/>
</connectionStrings>

Here we have to add AjaxControlToolkit assembly reference in our page
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

Then we have to create our aspx page like this

Designer source code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1
/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>AJAX Rating control</title>
    <style type="text/css">
body
{
margin:0px auto;
width:980px;
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif
background:#C9C9C9;
}
.blankstar
{
background-imageurl(images/blank_star.png);
width16px;
height16px;
}
.waitingstar
{
background-imageurl(images/half_star.png);
width16px;
height16px;
}
.shiningstar
{
background-imageurl(images/shining_star.png);
width16px;
height16px;
}
</style>
</head>
<body>
    <form id="form1" runat="server">  
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>   
   
    <asp:Rating ID="Rating1" runat="server" AutoPostBack="true" StarCssClass="blankstar"
        WaitingStarCssClass="waitingstar" FilledStarCssClass="shiningstar"
        EmptyStarCssClass="blankstar" OnChanged="Rating1_Changed">
    </asp:Rating>

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>,
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> 
    </form>
</body>
</html>

Note:
          Source code has been attached along with this article (No registration required). 
You can download and copy the required images for Rating Control.

C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = "0 Users have rated this Product";
        Label2.Text = "Average rating for this Product is 0";      
        if (!IsPostBack)
        {
            BindRatings();
        }
    }
    protected void Rating1_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
    {       
        con.Open();
        SqlCommand cmd = new SqlCommand("INSERT INTO UserRating(Rating) VALUES (@Rating)", con);
        cmd.Parameters.AddWithValue("@Rating"SqlDbType.Int).Value = Rating1.CurrentRating;
        cmd.ExecuteNonQuery();
        con.Close();
        BindRatings();
    }
    public void BindRatings()
    {
        int Total = 0;       
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT Rating FROM UserRating", con);       
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Total += Convert.ToInt32(dt.Rows[i][0].ToString());
            }
            int Average = Total / (dt.Rows.Count);
            Rating1.CurrentRating = Average;
            Label1.Text = dt.Rows.Count + " " + "Users have rated this Product";
            Label2.Text = "Average rating for this Product is" + " " + Convert.ToString(Average);
        }
    }
}


No comments:

Post a Comment