Monday, June 15, 2015

Using Ajax rating control inside Datalist in asp.net

Introduction: In this article I will explain how to use the Ajax rating control inside Datalist in asp.net.
Using Ajax rating control inside Datalist in asp.net

Description:
In this example hotels details is displayed and datalist control and users will rate it. To implement the functionality follow the below given steps:
Steps 1: Create 2 tables one to store the hotel detail (Tb_Hotel) and 2nd one have rating (Tb_Rating):

Create table Tb_Hotel
(
HotelID int identity not null,
HotelName varchar(100),
HotelDescription varchar(max),
Hotelimg varchar(max)
)
Create table Tb_Rating
(
HotelID int not null,
Rating int
)

Now create 2 store procedures to Insert and fetch the detail from database.
Store Procedure to insert the detail to table:
Create procedure Sp_InsertHotelRating
(
@id int,
@rating int
)
As begin
Insert into dbo.Tb_Rating(HotelID,Rating) values(@id,@rating)
End

Store procedure to fetch the records from table:
Create procedure Sp_GetHotelDetail

As Begin

Select Tb_Hotel.HotelID, Tb_Hotel.HotelName, Tb_Hotel.HotelDescription,Tb_Hotel.Hotelimg,
ISNULL(AVG(Tb_Rating.Rating),0) as rating from Tb_Hotel left outer join
dbo.Tb_Rating on Tb_Hotel.HotelId = Tb_Rating.HotelID group by
Tb_Hotel.HotelName,Tb_Hotel.HotelID,Tb_Hotel.HotelDescription,Tb_Hotel.Hotelimg
End

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

Steps 3: 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:DataList ID="dlhotel" runat="server" DataKeyField="HotelID">     
     <HeaderTemplate>  
     <table width="100%">  
          <thead><td><b>Hotel Name</b></td><td><b>Description</b></td><td>&nbsp;</td><td><b>Rating</b></td></thead>
     </HeaderTemplate>
            <ItemTemplate>           
            <tr><td><asp:Label ID="lblname" runat="server" Text='<%# Eval("HotelName") %>'></asp:Label></td>
    <td style="width: 30%;"><asp:Label ID="lbldescription" runat="server" Text='<%# Eval("HotelDescription") %>'></asp:Label></td>
    <td><asp:Image ID="hotelimage" runat="server" ImageUrl='<%# Eval("Hotelimg") %>' Width="250px"/></td>
    <td><asp:Rating ID="Rating1" runat="server" AutoPostBack="true" OnChanged="InsertRating" CurrentRating='<%# Eval("Rating") %>' MaxRating="5"  StarCssClass="ratingEmpty" WaitingStarCssClass="ratingSaved" EmptyStarCssClass="ratingEmpty" FilledStarCssClass="ratingFilled" >
       </asp:Rating></td></tr>
            </ItemTemplate>
        </asp:DataList></table>

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

Step 4: 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 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
        {
            int rowIndex = ((sender as AjaxControlToolkit.Rating).NamingContainer as DataListItem).ItemIndex;
            int hotelid = Convert.ToInt32(dlhotel.DataKeys[rowIndex].ToString());
            SqlCommand cmd = new SqlCommand("Sp_InsertHotelRating", con);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            cmd.Parameters.AddWithValue("@id", hotelid);
            cmd.Parameters.AddWithValue("@rating", e.Value);
            cmd.ExecuteNonQuery();           
            con.Close();
            cmd.Dispose();
            BindDatalist();
        }
        catch (Exception ex)
        {
        }
    }

VB:
    Protected Sub InsertRating(sender As Object, e As AjaxControlToolkit.RatingEventArgs)
        Try
            Dim rowIndex As Integer = TryCast(TryCast(sender, AjaxControlToolkit.Rating).NamingContainer, DataListItem).ItemIndex
            Dim hotelid As Integer = Convert.ToInt32(dlhotel.DataKeys(rowIndex).ToString())
            Dim cmd As New SqlCommand("Sp_InsertHotelRating", con)
            cmd.CommandType = CommandType.StoredProcedure
            con.Open()
            cmd.Parameters.AddWithValue("@id", hotelid)
            cmd.Parameters.AddWithValue("@rating", e.Value)
            cmd.ExecuteNonQuery()
            BindDatalist()
            con.Close()
            cmd.Dispose()
        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)
        {
            BindDatalist();
        }
    }
    public void BindDatalist()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Sp_GetHotelDetail", con);
            adp.SelectCommand.CommandType = CommandType.StoredProcedure;
            DataTable dt = new DataTable();
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                dlhotel.DataSource = dt;
                dlhotel.DataBind();
            }
        }
        catch (Exception ex)
        {
        }
    }

VB:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindDatalist()
        End If
    End Sub
    Public Sub BindDatalist()
        Try
            Dim adp As New SqlDataAdapter("Sp_GetHotelDetail", con)
            adp.SelectCommand.CommandType = CommandType.StoredProcedure
            Dim dt As New DataTable()
            adp.Fill(dt)
            If dt.Rows.Count > 0 Then
                dlhotel.DataSource = dt
                dlhotel.DataBind()
            End If
        Catch ex As Exception
        End Try
    End Sub
Now build, run the project and check the result.

download

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

2 comments: