Wednesday, June 10, 2015

Ajax rating control example in asp.net

Introduction: In this article I will explain how to use the Ajax rating control in asp.net with database.

Description:
We see an option for rating on shopping website like FlipKart, SnapDeal, and Amazon etc… There is a rating control using this we can display the rating. In this example I have an Hotel and users will rate it. To implement the functionality follow the below given steps:

Steps 1: Add the Ajax toolkit to Visual Studio if not added. How to add the

Steps 2: Add a webform to project/website. Now drag and drop the Rating Control from Toolbax and design the page as given below:

HTML markup of aspx page:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="pnlRating" runat="server">
<ContentTemplate>
<table width="100%">
<thead><tr><td align="center"><b>Hotel Name</b></td><td align="center"><b>Description</b></td><td ><b>Rating</p></td></tr></thead>
<tr>
<td align="center">Taj<img src="images/hotelimg.jpg" /></td>
<td align="center"><p style="text-align:justify">Enjoy a one-of-a-kind experience: the best service and facilities on Lanzarote
Unspoiled beaches, dream swimming pools and unique tropical gardens
Privileged climate all year round in one of Spain’s best resorts
Fine dining at the hotel on international, Mediterranean and signature specialties
Discover our service The Level, Meliá’s most exclusive commitment to luxury
Discover the exclusive private Villas unique on Lanzarote
Hotel designed by Fernando Higueras, Pritzker International Architecture Prize
Enjoy the new Beach Bar by the sea (opening times vary by season)
The hotel is part of Lanzarote’s Artistic and Cultural Heritage</p></td>
<td style="width:35%">
    <asp:Rating ID="Rating1" runat="server" AutoPostBack="true" MaxRating="5" OnChanged="InsertRating" StarCssClass="ratingEmpty" WaitingStarCssClass="ratingSaved" EmptyStarCssClass="ratingEmpty" FilledStarCssClass="ratingFilled">
    </asp:Rating>
<b> <asp:label ID="lblmessage" runat="server"/> </b>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>

In his example maximum rating value is 5 but we can change the maximum rating value using MaxRating property.
Note: Don’t forget to add the Scriptmanager. Rating control requires ScriptManager on page.

Step 3: Add the given style in head section of page:
  <style type="text/css">
      table tr td {
    padding:0 10px;
}
.ratingEmpty
{
background-image: url(images/ratingempty.png);
width:18px;
height:17px;
}
.ratingFilled
{
background-image: url(images/ratingfilled.png);
width:18px;
height:17px;
}
.ratingSaved
{
 background-image: url(images/ratingsaved.png);
width:18px;
height:17px;
}
</style>

Steps 4: Create a table Tb_Rating:
Create table Tb_Rating
(
HotelID int identity not null,
Rating int
)
Not create 2 store procedures to Insert and fetch the detail from database.

Store Procedure to insert the detail to table:
CREATE PROCEDURE InsertRating
(
@rating int
)
AS
BEGIN
           
            SET NOCOUNT ON;

    Insert into dbo.Tb_Rating values (@rating)
END

Store procedure to fetch the records from table:
CREATE PROCEDURE GetRating

As begin
Select ISNULL(AVG(Rating),0) as rating,count(*) as Totalcount from dbo.Tb_Rating
End

Steps 5: Write the below given code.
Add the Namespace:-
C#:
using System.Data;
using System.Data.SqlClient;
using System.Configuration; 
VB:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Connection:-
C#:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
 VB:
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())

Write the on OnChanged event of Rating control to insert and save to the database:
C#:
  protected void InsertRating(object sender, AjaxControlToolkit.RatingEventArgs e)
    {
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("InsertRating", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@rating", Rating1.CurrentRating);
            cmd.ExecuteNonQuery();
            con.Close();
            BindRating();
        }
        catch (Exception ex)
        {
        }
    }

VB:
Protected Sub InsertRating(sender As Object, e As AjaxControlToolkit.RatingEventArgs)
        Try
            con.Open()
            Dim cmd As New SqlCommand("InsertRating", con)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@rating", Rating1.CurrentRating)
            cmd.ExecuteNonQuery()
            con.Close()
            BindRating()
        Catch ex As Exception
        End Try
    End Sub

Code to Bind/display the Rating:
C#:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindRating();
        }
    }

protected void BindRating()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("GetRating", con);
            adp.SelectCommand.CommandType = CommandType.StoredProcedure;
            DataTable dt = new DataTable();
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                Rating1.CurrentRating = Convert.ToInt32(dt.Rows[0]["rating"]);
                lblmessage.Text = dt.Rows[0]["Totalcount"] + "user(s) have rated this Hotel";
            }
        }
        catch (Exception ex)
        {
        }
    }

VB:
   Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindRating()
        End If
    End Sub

Protected Sub BindRating()
        Try
            Dim adp As New SqlDataAdapter("GetRating", con)
            adp.SelectCommand.CommandType = CommandType.StoredProcedure
            Dim dt As New DataTable()
            adp.Fill(dt)
            If dt.Rows.Count > 0 Then
                Rating1.CurrentRating = Convert.ToInt32(dt.Rows(0)("rating"))
                lblmessage.Text = dt.Rows(0)("Totalcount") & "user(s) have rated this Hotel"
            End If
        Catch ex As Exception
        End Try

    End Sub

Now build ,run the project and check the result.
Result:
Ajax rating control example in asp.net

If you get any problem, you can download the working example of this:
Download

In this article we have learn to use the Ajax rating control. I hope you enjoyed this article. 

No comments:

Post a Comment