Aspdotnet-Suresh

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

JQuery Display/show average rating with decimal values from database in asp.net

Mar 2, 2012
Introduction:

In this article I will explain how to show average rating with decimal values in asp.net using JQuery.


Description:
  
In previous post I explained Ajax rating example with database in asp.net . If we use ajax rating control to display rating we have one disadvantage that is if we get average rating like 4.3 or 2.7 etc we don’t have chance to show rating based on that value because ajax rating supports only integer values to solve this problem I am writing this article to display average rating including decimal values using JQuery in asp.net.
To implement this concept first we need to design table in database and give name as Rating_Table

Column Name
Data Type
Allow Nulls
Id
int(set identity property=true)
No
Rating
float
Yes
UserName
varchar(50)
Yes
After completion table design create new website using visual studio and Right click on your website >> select Add New Item >> Select Generic Handler and give name as RatingHandler.ashx (Here I am using this name to connect with JQuery. If you want different name then change it in your aspx page also). After that write the following code in generic handler file (RatingHandler.ashx)  
 
C# Code
<%@ WebHandler Language="C#" Class="RatingHandler" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;

public class RatingHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Rating_Table(Rating,UserName) values(@rating,@name)", con);
cmd.Parameters.AddWithValue("@rating", context.Request.Form["rating"]);
cmd.Parameters.AddWithValue("@name", context.Request.LogonUserIdentity.Name);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("select count(Id) as NumberOfUsers,sum(Rating) as Total from Rating_Table", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
float COUNT = float.Parse(dt.Rows[0]["NumberOfUsers"].ToString());
float RATING = float.Parse(dt.Rows[0]["Total"].ToString());
context.Response.ContentType = "text/plain";
try
{
float result = RATING / COUNT;
context.Response.Write(result.ToString("0.0"));
}
catch (Exception ex)
{
context.Response.StatusCode = 202;
context.Response.Write(ex.Message);
context.Response.Flush();
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
If you observe above code once user click on stars their rating details insert into database and get those details from database to display average rating. This http handler gets rating details from page using context.Request.Form["rating"] statement.
VB.NET Code
<%@ WebHandler Language="VB" Class=" RatingHandler" %>

Imports System.Data
Imports System.Data.SqlClient
Imports System.Web

Public Class RatingHandler
Implements IHttpHandler

Public Sub ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("insert into Rating_Table(Rating,UserName) values(@rating,@name)", con)
cmd.Parameters.AddWithValue("@rating", context.Request.Form("rating"))
cmd.Parameters.AddWithValue("@name", context.Request.LogonUserIdentity.Name)
cmd.ExecuteNonQuery()
cmd = New SqlCommand("select count(Id) as NumberOfUsers,sum(Rating) as Total from Rating_Table", con)
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
Dim COUNT As Single = Single.Parse(dt.Rows(0)("NumberOfUsers").ToString())
Dim RATING As Single = Single.Parse(dt.Rows(0)("Total").ToString())
context.Response.ContentType = "text/plain"
Try
Dim result As Single = RATING / COUNT
context.Response.Write(result.ToString("0.0"))
Catch ex As Exception
context.Response.StatusCode = 202
context.Response.Write(ex.Message)
context.Response.Flush()
context.Response.[End]()
End Try
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
After completion of write code in HttpHandler add following code in your aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>jQuery Rater Plugin Demo</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery.rater.js"></script>
<script type="text/javascript">
$(function() {
$('#testRater').rater({ postHref: 'RatingHandler.ashx' });
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="testRater" class="stat">
<label for="rating">Rating</label>
<div class="statVal">
<span class="ui-rater">
<span class="ui-rater-starsOff" style="width:90px;"><span class="ui-rater-starsOn" runat="server" id="testSpan"></span></span>
<span class="ui-rater-rating" id="avgrating" runat="server"></span>&#160;(<span class="ui-rater-rateCount" id="userscount" runat="server"></span>)
</span>
</div>
</div>
</form>
</body>
</html>
If you observe above code in header section I added some of script and css files by using those files we have a chance to show average rating with decimal values. To get those files download attached sample code and use it in your application.

Another thing here we need to know is script function in header section

$('#testRater').rater({ postHref: 'RatingHandler.ashx' });
Here I given div id and path of handler by using these details we will save user rating details and display average rating with decimal values.

After completion of aspx page design add the following namespaces in code behind

C# Code


using System;
using System.Data;
using System.Data.SqlClient;
After that write the following code in code behind


protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select count(Id) as NumberOfUsers,sum(Rating) as Total from Rating_Table", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
float count=0,rating=0,result=0;

if( Convert.ToInt32(dt.Rows[0]["NumberOfUsers"].ToString())!=0 )
{
count = float.Parse(dt.Rows[0]["NumberOfUsers"].ToString());
rating = float.Parse(dt.Rows[0]["Total"].ToString());
result = Convert.ToInt32(Math.Ceiling((rating / count) * 18));
avgrating.InnerText = Math.Round((rating / count), 1).ToString();
}
else
{
avgrating.InnerText = "0";
}
testSpan.Style.Add("width", result+"px");
userscount.InnerText = count.ToString();
}
VB.NET Code

Imports System.Data
Imports System.Data.SqlClient

Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("select count(Id) as NumberOfUsers,sum(Rating) as Total from Rating_Table", con)
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
Dim count As Single = 0, rating As Single = 0, result As Single = 0

If Convert.ToInt32(dt.Rows(0)("NumberOfUsers").ToString()) <> 0 Then
count = Single.Parse(dt.Rows(0)("NumberOfUsers").ToString())
rating = Single.Parse(dt.Rows(0)("Total").ToString())
result = Convert.ToInt32(Math.Ceiling((rating / count) * 18))
avgrating.InnerText = Math.Round((rating / count), 1).ToString()
Else
avgrating.InnerText = "0"
End If
testSpan.Style.Add("width", result & "px")
userscount.InnerText = count.ToString()
End Sub
End Class


Demo


Download sample code attached


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 RSS subscribe by email Subscribe by Email

19 comments :

abhinav bajpai said...

Fabulous work sir ,great fan of you..

abhinav bajpai said...

Fabulous work sir ,great fan of you..

Anonymous said...

Sir You Are Best Best Best Programmer For Me
Thank you Sir
Your Friend Rahul Shimpi

Jack said...

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)


my web.config file is

what is problem

Suresh Dasari said...

@Jack...
That problem because of database connection check this link SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"); Here i given my database connection please change this one and give your database connection string to connect your database. If that is not solved then check this post http://www.aspdotnet-suresh.com/2011/11/network-related-or-instance-specific.html

Robin Jackman said...

Thanks for the great info you have done a great job.Keep sharing

Anonymous said...

Thank you a lot! But can you tell, is it possible to implement rating in asp.net datalist items?

koteswar rao said...

very thnks....g8

Akiii said...

its great, thanks suresh !

Anonymous said...

thanks for your valuable posts

Deep!

Yasser Zaid said...

Good Example but what if i want to pass another Parameter like ID of Post for example

Thank you

madhuri said...

Sir my NumberOfUsers=2 and Rating=31...your above code not working properly for me..

Suresh Dasari said...

@madhuri...
Above code working fine. Please check your code I hope there is a problem with your code only....

Anonymous said...

Dear suresh,
I am heartly resiprocte for your posts..........

Manas Mohapatra said...

Nice Article. Keep it up...

aliensoul said...

Hi, i am trying to implement where clause into Handler, and it gives me error. I put in that table
PostID so whatever i put there it gives me error.
Can anyone help me

Anonymous said...

For me! you are my mentor, guru whatever you call it! I love you sir!! you are G.R.E.A.T!! You have saved alot of our time and energy by simply making us come to your site and get what we need! this is just awesome!! I love this site!! :))

Anonymous said...

The code is running fine but Rating
3.7 (NaN) why NaN is showing and the the page_load function in aspx.cs file not load the old data please help
it show 0 always

Cat Blog said...

@Suresh, great example. Do you have any example where you pass ID as a parameter?

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.