Here I will explain how to use Ajax rating control with database to display average rating for particular article using asp.net
Description:
Previously I explained how to use Ajax Collapsible panel . Now I will explain how to use Ajax rating control with Database in asp.net. In many sites we will see rating options for books, articles and movies etc by giving rating option to user we have chance to know about particular thing how much users are feeling comfort with particular thing. In Ajax we have a rating control by using that we can display the rating option easily. Here I am storing each user rating details into database and displaying the average rating based on number of users rating. To achieve this first design one table in your database and give name like RatingDetails if you want to give another name you can but you need to change table name in code also.
Column Name
|
Data Type
|
Allow Nulls
|
Id
|
Int(Set Identity=true)
|
No
|
Rate
|
int
|
Yes
|
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!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 Sample</title>
<style type="text/css">
.ratingEmpty
{
background-image: url(ratingStarEmpty.gif);
width:18px;
height:18px;
}
.ratingFilled
{
background-image: url(ratingStarFilled.gif);
width:18px;
height:18px;
}
.ratingSaved
{
background-image: url(ratingStarSaved.gif);
width:18px;
height:18px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="ScripManager1" runat="server"/>
<div>
<asp:UpdatePanel ID="pnlRating" runat="server">
<ContentTemplate>
<table width="35%">
<tr>
<td width="27%">
<b>Average Rating:</b>
</td>
<td>
<ajax:Rating ID="ratingControl" AutoPostBack="true" OnChanged="RatingControlChanged" runat="server" StarCssClass="ratingEmpty" WaitingStarCssClass="ratingSaved" EmptyStarCssClass="ratingEmpty" FilledStarCssClass="ratingFilled">
</ajax:Rating>
<b> <asp:label ID="lbltxt" runat="server"/> </b>
</td>
</tr>
<tr>
<td colspan="2">
aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
|
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
|
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindRatingControl();
}
}
protected void RatingControlChanged(object sender, AjaxControlToolkit.RatingEventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into RatingDetails(Rate)values(@Rating)",con);
cmd.Parameters.AddWithValue("@Rating", ratingControl.CurrentRating);
cmd.ExecuteNonQuery();
con.Close();
BindRatingControl();
}
protected void BindRatingControl()
{
int total = 0;
DataTable dt = new DataTable();
con.Open();
SqlCommand cmd = new SqlCommand("Select Rate from RatingDetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
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);
ratingControl.CurrentRating = average;
lbltxt.Text = dt.Rows.Count+"user(s) have rated this article";
}
}
|
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindRatingControl()
End If
End Sub
Protected Sub RatingControlChanged(ByVal sender As Object, ByVal e As AjaxControlToolkit.RatingEventArgs)
con.Open()
Dim cmd As New SqlCommand("insert into RatingDetails(Rate)values(@Rating)", con)
cmd.Parameters.AddWithValue("@Rating", ratingControl.CurrentRating)
cmd.ExecuteNonQuery()
con.Close()
BindRatingControl()
End Sub
Protected Sub BindRatingControl()
Dim total As Integer = 0
Dim dt As New DataTable()
con.Open()
Dim cmd As New SqlCommand("Select Rate from RatingDetails", con)
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
total += Convert.ToInt32(dt.Rows(i)(0).ToString())
Next
Dim average As Integer = total \ (dt.Rows.Count)
ratingControl.CurrentRating = average
lbltxt.Text = dt.Rows.Count & "user(s) have rated this article"
End If
End Sub
End Class
|
<connectionStrings>
<add name="dbConnection" connectionString="Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true"/>
</connectionStrings>
|
|
|
|
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
Subscribe by RSS
Subscribe by Email
|
|||
|
|


Subscribe by RSS
Subscribe by Email
33 comments :
hi..
This article was very helpful to me...But how to display the rating stars in decimal..plz could u send me the code...
Hi,
this article was very helpful but this rating control is shown how many user's rate this article .... I have different scenario let suppose we have 20 pages in our website each page have rating control so how we managed this not user wise but pages wise each page have different id and posts in website have different id...
Please help me to solve this ...
Thanks advance for this
How to make star visible ?????????
Hi Suresh,
This is exactly what I am looking for, but I am not versed in C#. Can you rework the code for use with a VB project?
Thanks,
Kerron (defkerron@yahoo.com)
@Kerron,
i added VB code also please check the post.
thanks bro, much appreciated
i like this site.this was very useful.keep going
I appreciate the VB code. Just what I needed. thanks.
Great example; I was wondering how would you program the VB code behind if there was a 3rd data colum "ContentId"(int) to sort the average rating by contentID... I really stuck any ideas?
Thanks, Jm
Hello! I get this messages. Please let me know how to fix it.
Thank you
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Hi! Thank you for your job! All working. But i can't add a few ratings on the same page. How to do that? Please help.
Regards
Max
Its too much good Article..........
nice post
@Comment 10
that error because of your sql connection failure check this post to solve that problem
http://www.aspdotnet-suresh.com/2011/11/network-related-or-instance-specific.html
hi suresh nice post but stars are not visible for why please tell me
this is good,but without using database how i can implement this
very good article,honey chawla
Error: Could not load type 'System.Web.UI.ScriptReferenceBase' from assembly 'System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
I use ASP.net V3.5
it's good
please send me AJAX PPTS
stars in not visiable during runing time why tell me
Thanks so much for all you write. Do you have an example of how to insert ratings into database from gridview and get average?
awesome article man.Thanx a lot
Gud One Sir :-) :)
How to use onclientcallback with Ajax Rating control?
Hi Suresh very nice article...i need to change the rating when it is kept inside datalist...suggestions plz.....
suresh sir im use
protected void rating()
{
int total = 0;
DataTable dt = new DataTable();
con.Open();
SqlCommand cmd = new SqlCommand("Select Rate from Rating_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
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);
ratingControl.CurrentRating = average;
lbltxt.Text = dt.Rows.Count + "user(s) have rated this article";
}
this method but when i debug code breakpoint not going in if condition after da.Fill(dt); it out
suresh sir im use
protected void rating()
{
int total = 0;
DataTable dt = new DataTable();
con.Open();
SqlCommand cmd = new SqlCommand("Select Rate from Rating_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
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);
ratingControl.CurrentRating = average;
lbltxt.Text = dt.Rows.Count + "user(s) have rated this article";
}
this method but when i debug code breakpoint not going in if condition after da.Fill(dt); it out
iam using asp.net 2.0 with ajaxcontrol 1.0
hi suresh
it is good .. very good
sadfasdfasdf
hai suresh can u explain how to give rating using button click
i am using same thing in Datalist but it's now working , ther is any other way to use it in the datalist ..!!!
hi suresh sir,,,
how we use data list control in three tier,how we declare the datalist in .cs page and dal,bal .