This is part two of the ASP.NET Content Rater Web Site series. In this tutorial we will add the functionality for the user to apply their ratings to the content in ASP.NET 4.0 and C#.

Connecting to the Database

To begin setting up our rating functionality, we will first need to connect to our database. We will need to add in a connection string to our Web.Config file. To do this, open up the Web.Config file for editing and add the following code in between the and tags:

Displaying the Content

Next, we need to display the content to our users so that they will be able to rate it. To do this, we will be creating a data table in code that we will populate with the appropriate data from our database. Then, we will display this in a table within the repeater that we added to our home page. First, we need to begin creating our data table when the page loads. To do this, open Default.aspx.cs up for editing and add the following code to the Page_Load event method:

This code will populate our data table with the titles and authors of the books from our database. Then, it checks to see if the user is logged in. If they are, the ratings for that specific user are then added to our data table.

Next, we need to add in a table to our repeater to which we will display this data. To do this, open up the Default.aspx page in source mode and add the following code to our repeater:

This code creates a table with three columns, a title, author, and rating column. Then, it adds the title and author of each book to the appropriate column. Finally, it adds drop down lists with the options of 1 through 5 in them with the current user’s ratings selected.

Submitting Ratings

If you take a look at our repeater code, you will notice that the drop down list has its OnTextChanged property set to ‘SubmitRating’. What this does is call the SubmitRating method whenever the user changes the index of one of the drop down lists. It is this method that we will need to add to actually submit the user’s selected rating to the database. To do this, add the following method to our Default.aspx.cs class:

This code checks to make sure that a valid user and rating have been set. Then, it uses a SQL command to insert a new entry if the rating does not exist in the database. If the rating already existed, it updates it to the new value.


To test this out, go ahead and load up the website. Login to the account that you created earlier and begin giving the books ratings by selecting a number between 1 and 5 for each of them. Then, close the web site and reload it. Login again and notice that it populated the ratings based on what you entered previously. This is a simple way to allow your users to rate content on your web site.
Download Source Files