This is a migrated thread and some comments may be shown as answers.

Only one empty star displaying

7 Answers 147 Views
Rating
This is a migrated thread and some comments may be shown as answers.
Sauge
Top achievements
Rank 1
Sauge asked on 30 Mar 2013, 01:05 PM
Hi there

I am probably doing something really stupid or not understanding how to link up to the datasource properly but I have been working on this for a couple of days and I can't seem to work out how to get the rating to work with a datasource.

I have a stand alone rating control on my page that I wanted to link up to an  accessdatasource that would display the current rating.  (I also want to be able to allow users to rate using the same control and save the value into the database too, but that's another story)

Here is what I have

<div id="info">
            Hover over image for options and info <table id="rating">
                <tr>
                    <td>Rate this album:</td><td>
                        <telerik:RadRating ID="RadRating1" runat="server" AutoPostBack="True" Skin="Metro" DataSourceID="AccessDataSource3" Precision="Item" AppendDataBoundItems="True">
                            <ItemBinding ValueField="AverageRatingRounded"></ItemBinding>                                 
                        </telerik:RadRating>
                    </td>
                </tr>
            </table>
        </div>
 
 
 
 <asp:AccessDataSource ID="AccessDataSource3" runat="server" DataFile="~/App_Data/ASPNetDB.accdb"
        SelectCommand="SELECT AlbumID, CountRating, Totalrating, SUM(Totalrating) / CountRating AS AverageRating, ROUND(AverageRating, 0) AS AverageRatingRounded FROM qryRating GROUP BY AlbumID, CountRating, Totalrating HAVING (AlbumID = ?)"><SelectParameters>
            <asp:QueryStringParameter Name="AlbumID" QueryStringField="albumID" Type="Int32" />
        </SelectParameters>
         
    </asp:AccessDataSource>

As you can see, the datasource is based on a query which works out how many times the album has been rated and what the average rating is already, (by counting times rated, adding up all the ratings and dividing the total ratings by the count of times rated, then by rounding to whole value)

All that displays though is one empty star (if I hover over it, it does display the average rating though)

I have looked at EVERY demo and documentation on databinding for the rating control but I just can't seem to get my head around what I should be doing.

Please, please, please point me in the right direction before I pull all my hair out and bite my nails down to the quick

Thank you in advance


7 Answers, 1 is accepted

Sort by
0
Slav
Telerik team
answered on 03 Apr 2013, 05:05 PM
Hi Sauge,

Please check the online demo Rating - Data Binding. The first example shows your current setup of the RadRating. The DataSourceID property of the control points to an ASP.NET DataSource control, which is used for populating the items in the rating and their values. For example, if the data source returns 6 items, the rating will have 6 items.

The third example shows how to use the DbValue property of the rating for setting the current value of the control with data that is pulled from a data source. According to your description, this is what you want to achieve so I would suggest setting this property in the code-behind with the result of your SQL query.

Regards,
Slav
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
0
Sauge
Top achievements
Rank 1
answered on 04 Apr 2013, 08:57 AM
Hi Slav

Thank you for your reply, I had looked at that demo before but I am totally confused and still in the dark.

What I am confused about mostly is what I should be returning from the database.  At the moment I am returning 1 row which has 2 columns. The ID of the Album (AlbumID) and the average rating for that Album (AverageRatingRounded ) all worked out by a query/view in the access database. 

Shouldn't/isn't there an easy way just to hook up the rating control to the AverageRatingRounded value returned from the database via the Accessdatasource so that it will display this value as stars, without doing this from code behind?  For example if the value returned was 3 then 3 stars would be filled in and the other 2 empty but still displaying 5 stars.  Or would I need to do it in code behind, and if so how?

Or should I be returning some other value "if the data source returns 6 items, the rating will have 6 items."?  At the moment, I am presuming that when a user will rate an album, then they would click the stars and the value will be stored as a separate row in the database. Is there is some other way that this should be done that I am not thinking about?

Perhaps I am being really dim, but I don't understand how I would display the average rating in stars if I am returning more than one row from the database. (see how confused I am :-(  )

I am a bit of a newbie so please forgive my ignorance regarding this

I would be really grateful if you could you explain to me how I can do this relevant to my situation. 
0
Accepted
Slav
Telerik team
answered on 09 Apr 2013, 08:19 AM
Hello Sauge,

Setting DataSourceID is not needed in your case. I would suggest removing it from the setup of the RadRating.

In the code-behind of your page add the following code:
DataView dvAccess = (DataView)AccessDataSource3.Select(DataSourceSelectArguments.Empty);
RadRating1.DbValue = dvAccess[0]["AverageRatingRounded"];

It will retrieve the row of data that is returned by the AccessDataSource. Then it will pass the value of the column AverageRatingRounded to the property DbValue of RadRating. As a result, the rating on your page should display the value of AverageRatingRounded from the datasource. Note that this sample is based on the code you provided and the information from your previous post. If you have made additional changes, you should update the code sample accordingly, for example if the name of the column is modified.

When you select a value of the rating by clicking on its items, it will not be updated in the database automatically. You will need to handle the server-side event Rate in order to get the selected value and write it in your datasource. The online demo Rating - Rate and Leave a Comment shows how to do this.

Greetings,
Slav
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
0
Sauge
Top achievements
Rank 1
answered on 09 Apr 2013, 10:15 AM
Hi Slav,

Thank you SO much, I am very grateful to you,

BUT...

 I can now display the current average rating as stars from the database using the following code with autoeventwireup = "true":

Private Sub Page_Load(sender As Object, e As System.EventArgs)
 
       Dim dvAccess As DataView = DirectCast(AccessDataSource3.[Select](DataSourceSelectArguments.Empty), DataView)
       RadRating1.DbValue = dvAccess(0)("AverageRatingRounded")
 
   End Sub

But if I try to rate using the following code:

Protected Sub RadRating1_Rate(sender As Object, e As EventArgs)
 
       Dim ConnString As String = GetConnString()
 
       Dim rating As RadRating = DirectCast(sender, RadRating)
       Dim oRating As Decimal = rating.Value
       Dim useralbum As Int32 = (Request.QueryString("albumID"))
       Dim SqlString As String = "INSERT INTO [tblRatings] ([AlbumID], [Rating]) VALUES (?, ?)"
 
       Using conn As New OleDbConnection(ConnString)
 
           Using cmd As New OleDbCommand(SqlString, conn)
 
               cmd.CommandType = CommandType.Text
 
               conn.Open()
 
               cmd.Parameters.AddWithValue("AlbumID", useralbum)
               cmd.Parameters.AddWithValue("Rating", oRating)
 
 
               cmd.ExecuteNonQuery()
 
 
           End Using
 
       End Using
 
 
 
   End Sub


No matter what I do, the rating inserted into the database is always the same as the average rating that comes from the database on page load.

If I set autoeventwireup to false, then I can rate, and the correct value is inserted into the database but I am unable to display the current average rating as stars and all the stars are always empty, except of course just after I rate and then the amount of stars clicked persists

<div id="info">
            Hover over image for options and info
            <table id="rating">
                <tr>
                    <td>Rate this album:</td>
                    <td>
                        <telerik:RadRating ID="RadRating1" runat="server" ItemCount="5" AutoPostBack="True" OnRate="RadRating1_Rate" ></telerik:RadRating>
                    </td>
                    <td>
                       
 
                    </td>
                </tr>
            </table>
        </div>

What am I doing wrong or what do I need to do to be able to display the average rating on page load with the first datasource, but still be able to rate and insert the new clicked values into the database, but then display the average rating once again?

Thank you in advance for your help


0
Sauge
Top achievements
Rank 1
answered on 13 Apr 2013, 10:56 AM
Ignore that last post
I had a typo and now all is working perfectly
Thank you again :-)
0
Andrew
Top achievements
Rank 1
answered on 15 Dec 2014, 09:53 PM
Hello,

Sorry to revive an older post but I am having a similar issue as Sauge. Everything seems to be working except that I have two labels and I'm getting the wrong rating in my "Your rating is" label. The average rating works fine and displays in the second label. Also, the stars display the correct average on page load. But as soon as I choose a rating, it displays the AVERAGE of the average and what I rated.

For example: If there is an average of 3.6 on page load and then I rate a 5, it will display 3.642857 in the "Your rating is" label.

I have posted the code below. Any help would be greatly appreciated!

Imports System
Imports System.Collections.Generic
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
 
Imports Telerik.Web.UI
Imports System.Data
Imports System.Data.SqlClient
 
Partial Public Class _2014
    Inherits System.Web.UI.Page
 
    Protected Sub RadRating_Rate(sender As Object, e As EventArgs)
        Dim rating As RadRating = DirectCast(sender, RadRating)
        If rating.ID = "RadRating1" Then
 
            Label1.Text = "Your Rating is: " + "<span style='color:Red'>" + RadRating1.Value.ToString + "</span>"
 
            AddRating(RadRating1.Value, "Amanda", 20141)
        End If
 
        If rating.ID = "RadRating2" Then
 
        End If
 
        If rating.ID = "RadRating3" Then
 
        End If
        If rating.ID = "RadRating4" Then
 
        End If
 
    End Sub
 
 
    Public Sub AddRating(ByVal rateVal As Object, ByVal picName As String, ByVal picId As Integer)
 
        Dim cnstr2 = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString())
        Dim cmd2 = New System.Data.SqlClient.SqlCommand("INSERT INTO Ratings(Rating,CreateDate,name,PicID) VALUES (@rating, @date , @name, @picID)", cnstr2)
        cmd2.CommandType = System.Data.CommandType.Text
        cmd2.Parameters.AddWithValue("@rating", rateVal)
        cmd2.Parameters.AddWithValue("@date", Date.Now)
        cmd2.Parameters.AddWithValue("@name", picName)
        cmd2.Parameters.AddWithValue("@picID", picId)
        'cmd2.Parameters.AddWithValue("@ip", ip)
 
        cnstr2.Open()
 
        cmd2.ExecuteNonQuery()
        cnstr2.Close()
 
    End Sub
 
    Public Function GetCount(ByVal picID As Integer) As Decimal
        Dim theCount As Decimal = 0.0
 
        'Dim currentAverageRating As Object = Vehicles.Rows(dataItem.ItemIndex + RadGrid1.CurrentPageIndex * RadGrid1.PageSize)(2)
        Dim cnstr2 = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString())
        Dim rdr As SqlDataReader
        Dim cmd2 = New System.Data.SqlClient.SqlCommand("SELECT AVG(Rating) AS Total FROM Ratings  WHERE PicID = @picID ", cnstr2)
        cmd2.CommandType = System.Data.CommandType.Text
        cmd2.Parameters.AddWithValue("@picID", picID)
        cnstr2.Open()
 
        rdr = cmd2.ExecuteReader
 
        If rdr.HasRows Then
 
            rdr.Read()
            If Not IsDBNull(rdr.GetValue(rdr.GetOrdinal("Total"))) Then
                theCount = rdr.GetValue(rdr.GetOrdinal("Total"))
            End If
        End If
        rdr.Close()
 
        cnstr2.Close()
        Return theCount
    End Function
 
 
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
 
        RadRating1.DbValue = GetCount(20141)
 
        'Label1.Text = "Your Rating is: " + "<span style='color:Red'>" + RadRating1.Value.ToString + "</span>"
        Label2.Text = "Average Rating is: " + "<span style='color:Red'>" + Convert.ToString(Format(GetCount(20141), "#.#")) + "</span>"
    End Sub
 
 
End Class

Here is the radrating with the two labels in HTML:
<telerik:RadRating ID="RadRating1" Precision="Item" Value="0" ItemCount="5" runat="server" AutoPostBack="true" OnRate="RadRating_Rate">
                        </telerik:RadRating>
                        <asp:Label ID="Label1" runat="server" ForeColor="Green"></asp:Label>
                        <asp:Label ID="Label2" runat="server" ForeColor="Green"></asp:Label>
0
Ianko
Telerik team
answered on 19 Dec 2014, 07:33 AM
Hi Andrew,

The encountered behavior is quite trivial. After the RadRating is clicked, a post back is performed. Firstly, on page load, the rating's value is overridden:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
         ...
        RadRating1.DbValue = GetCount(20141)
         ...
End Sub

After that, the RadRating_Rate method is raised, and the value at this moment is the same as the one returned from the GetCount() method, because it always overrides the rotator's value. 

As a result, no matter what the user rates, the Average Value returned is repeated, i.e., the AddRating() methods always adds the same average value to the same item, and thus causes a faulty calculation.

The resolution is quite trivial too, basically, on load, the rotator's value should be set to the average one only if it is not a post back, subsequently, the user rating will call the RadRating_Rate. At this point the value of the rating must be preserved and after calling the AddRating method with the correct value, additional line should be added into the RadRating_Rate method to override the rating's value based on the new average calculation.

The following is something that should work as example (DB binding is removed, so that I could be able to examine the code properly):
Protected Sub RadRating_Rate(sender As Object, e As EventArgs)
    Dim rating As RadRating = DirectCast(sender, RadRating)
    If rating.ID = "RadRating1" Then
        Label1.Text = "Your Rating is: " + "<span style='color:Red'>" + RadRating1.Value.ToString + "</span>"
 
        AddRating(RadRating1.Value, "Amanda", 20141)
    End If
 
    If rating.ID = "RadRating2" Then
 
    End If
 
    If rating.ID = "RadRating3" Then
 
    End If
    If rating.ID = "RadRating4" Then
 
    End If
 
    RadRating1.DbValue = GetCount(20141)
 
End Sub
 
 
Public Sub AddRating(ByVal rateVal As Object, ByVal picName As String, ByVal picId As Integer)
 
    'Dim cnstr2 = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString())
    'Dim cmd2 = New System.Data.SqlClient.SqlCommand("INSERT INTO Ratings(Rating,CreateDate,name,PicID) VALUES (@rating, @date , @name, @picID)", cnstr2)
    'cmd2.CommandType = System.Data.CommandType.Text
    'cmd2.Parameters.AddWithValue("@rating", rateVal)
    'cmd2.Parameters.AddWithValue("@date", Date.Now)
    'cmd2.Parameters.AddWithValue("@name", picName)
    'cmd2.Parameters.AddWithValue("@picID", picId)
    ''cmd2.Parameters.AddWithValue("@ip", ip)
 
    'cnstr2.Open()
 
    'cmd2.ExecuteNonQuery()
    'cnstr2.Close()
 
End Sub
 
Public Function GetCount(ByVal picID As Integer) As Decimal
    Dim theCount As Decimal = 0.0
 
    'Dim currentAverageRating As Object = Vehicles.Rows(dataItem.ItemIndex + RadGrid1.CurrentPageIndex * RadGrid1.PageSize)(2)
    'Dim cnstr2 = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString())
    'Dim rdr As SqlDataReader
    'Dim cmd2 = New System.Data.SqlClient.SqlCommand("SELECT AVG(Rating) AS Total FROM Ratings  WHERE PicID = @picID ", cnstr2)
    'cmd2.CommandType = System.Data.CommandType.Text
    'cmd2.Parameters.AddWithValue("@picID", picID)
    'cnstr2.Open()
 
    'rdr = cmd2.ExecuteReader
 
    'If rdr.HasRows Then
 
    '   rdr.Read()
    '   If Not IsDBNull(rdr.GetValue(rdr.GetOrdinal("Total"))) Then
    '       theCount = rdr.GetValue(rdr.GetOrdinal("Total"))
    '   End If
    'End If
    'rdr.Close()
 
    'cnstr2.Close()
    Return 2
End Function
 
 
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If (Not Page.IsPostBack) Then
        RadRating1.DbValue = GetCount(20141)
    End If
 
 
    'Label1.Text = "Your Rating is: " + "<span style='color:Red'>" + RadRating1.Value.ToString + "</span>"
    Label2.Text = "Average Rating is: " + "<span style='color:Red'>" + Convert.ToString(Format(GetCount(20141), "#.#")) + "</span>"
End Sub

Regards,
Ianko
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
Tags
Rating
Asked by
Sauge
Top achievements
Rank 1
Answers by
Slav
Telerik team
Sauge
Top achievements
Rank 1
Andrew
Top achievements
Rank 1
Ianko
Telerik team
Share this question
or