CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » Article » jQuery Article » Creating a Simple Rating control using jQuery and AJAX in ASP.Net   You are not logged in.
Search
 

Technologies
 

Sponsors
 

CodeDigest Navigation
 

Technology News
 

Community News
No News Feeds available at this time.
 
Creating a Simple Rating control using jQuery and AJAX in ASP.Net

By Bala Murugan
Posted On April 18,2010
Article Rating: (Login)
Average Rating: 4
No of Ratings: 1
No of Comments: 0
Print this article.
Category: ASP.Net/jQuery

Subscribe to our feed!

Creating a Simple Rating control using jQuery and AJAX in ASP.Net

 

It is very important to capture the visitor’s or customer’s feedback in terms of rating in any public facing websites like shopping, news, reviews or article, etc.  This rating will help everyone to understand the credibility and worthiness of our website’s products. There are some handful free controls already available including a rating control in Ajax control toolkit.

 

In this article, we will try to build a very simple rating control ourselves using jQuery, Ajax and HttpHandler in ASP.Net. I said it’s a simple rating control because we will use RadioButtonList and DropDownList control to capture the user’s rating. Something like below,

 

Using RadioButtonList control

Ajax Rating control using RadioButtonList control in ASP.Net

 

Using DropDownList control

Ajax Rating control using DropDownList control in ASP.Net

 

Read the below FAQ’s to have a quick understanding on jQuery library.

What is jQuery? How to use it in ASP.Net Pages?

How to enable jQuery intellisense in Visual Studio 2008?

How to use jQuery intellisense in an external javascript file?

 

and the below article,

Introduction to jQuery in ASP.Net and 10 Advantages to Choose jQuery

 

I will create the rating control as user control so that it can be used anywhere in your project.

 

Steps

1.      Open Visual Studio 2008.

2.      Create a new “ASP.Net Web Site”.

3.      Include a new user control in your project by right clicking the solution and clicking “Add New Item...” dialog box.  Select Web user control and rename it accordingly. I have named it as SimpleRating.ascx.

4.      Grab the new jquery library from here. Create a folder called _scripts and copy the jquery library. Refer the above FAQ’s to know more.

 

Building Rating Control

Since, we use jquery library and Ajax method in our rating control we will need the item id in the client side to record the rating against the item in the server. For this purpose, we will include a HiddenField in our user control which can hold the itemid to the client side.  We will also include a panel control to populate the rating control (DropDownList or RadioButtonList) depending on the preference set in the rating control.

 

Refer the below code,

SimpleRating.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SimpleRating.ascx.cs" Inherits="SimpleRating" %>

<div class="Rating">

<asp:HiddenField ID="hfItemID" runat="server" />

<div id="dvCurrentRate"><b>Current Rating:</b> <% =CurrentRating %></div>

Your rating:

<asp:Panel ID="plRateCtrl" runat="server">

</asp:Panel>

</div>

 

In our user control, we will expose the below 5 public properties to configure the rating control.     

1.      MaxRate

This takes an integer and will dictate the maximum rate the rating control will allow.

2.      ItemID

This property will hold the ID of the item against which you want to rate. For example, if it is news site it will be newsid, article id for article site, etc.

3.      CurrentRating

Set this property with the current average rating for the item when rendering the page to the user. See the above figure.

4.      IsReadOnly

This will make the rating control to readonly.

For example, set this property to true if the user has already rated this item. Set it to false if you want the user to rate only after authenticating.

5.      RatingControl

This takes either DropDownList or RadioButton and renders the rating control accordingly in the Panel.

 

Refer the below code,

SimpleRating.ascx.cs

using System;

using System.Collections.Generic;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class SimpleRating : System.Web.UI.UserControl

{

    int _maxrate = 5;

    RateControl _rateControl = RateControl.DropDownList;

    bool _isReadOnly = false;

    int _currentRate;

    int _itemid;

 

    public int MaxRate

    {

        get

        {

            return _maxrate;

        }

        set

        {

            _maxrate = value;

        }

    }

    public int ItemID

    {

        get

        {

            return _itemid;

        }

        set

        {

            _itemid = value;          

            hfItemID.Value = value.ToString();

        }

    }

    public int CurrentRating

    {

        get

        {

            return _currentRate;

        }

        set

        {

            _currentRate = value;

        }

    }

    public bool IsReadOnly

    {

        get

        {

            return _isReadOnly;

        }

        set

        {

            _isReadOnly = value;

        }

    }

    public RateControl RatingControl

    {

        set

        {

            if (!Page.IsPostBack)

            {

                _rateControl = value;

                if (value == RateControl.DropDownList)

                {

                    DropDownList ddl = new DropDownList();

                    ddl.Items.Add(new ListItem("Rate", ""));

                    for (int i = 1; i <= MaxRate; i++)

                    {

                        ddl.Items.Add(new ListItem(i.ToString(), i.ToString()));

                    }

                   

                    if (IsReadOnly)

                        ddl.Enabled = false;

 

                    plRateCtrl.Controls.Add(ddl);

 

                }

                else

                {                  

 

                    RadioButtonList rdbList = new RadioButtonList();

                    rdbList.RepeatLayout = RepeatLayout.Flow;

                    rdbList.RepeatDirection = RepeatDirection.Horizontal;

                    for (int i = 1; i <= MaxRate; i++)

                    {

                        rdbList.Items.Add(new ListItem(i.ToString(), i.ToString()));

                    }

                    if (IsReadOnly)

                        rdbList.Enabled = false;

 

                    plRateCtrl.Controls.Add(rdbList);                

 

 

                }

            }

        }

    }

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsReadOnly)

        {

            if (!Page.ClientScript.IsClientScriptIncludeRegistered("jquery"))

                Page.ClientScript.RegisterClientScriptInclude("jquery", "_scripts/jquery-1.4.1.min.js");

 

            if (!Page.ClientScript.IsClientScriptIncludeRegistered("RatingEngine"))

                Page.ClientScript.RegisterClientScriptInclude("RatingEngine", "_scripts/SimpleRating.js");

        }

 else

        {

            plRateCtrl.Enabled = false;

        }

 

    }

}

public enum RateControl

{

    DropDownList,

    RadioButton

}

 

In the above code, setting DropDownList in RatingControl property will render dropdownlist control in the panel and setting RadioButtonList will render RadioButtonList control in the panel. We will use jquery to read the user rating and sending it to server.

To record the rating, we will create a simple HttpHandler which will accept itemid and user rating to record into the database.  Refer the below code,

 

RateHandler.ashx

<%@ WebHandler Language="C#" Class="RateHandler" %>

 

using System;

using System.Web;

using System.Text;

 

public class RateHandler : IHttpHandler {

   

    public void ProcessRequest (HttpContext context) {

 

        //If user is not authenticated then return, dont save rating!

        //if (!context.Request.IsAuthenticated)

        //{

        //    return;

        //}

       

       string ItemID = context.Request.QueryString["ItemID"];

       string Rate = context.Request.QueryString["Rate"];

       string user = context.User.Identity.Name;

         

        //Insert the rating to database and return the average of ratings for the itemid     

        //In your SP, check if the user has already rated to prevent duplicate rating

       

       

       int CurrentRating = 3; /*Should be returned from SP*/

       

       //Return the average rating in JSON to client

        

       StringBuilder jsonOutput = new StringBuilder();

       jsonOutput.AppendLine("[{");

       jsonOutput.AppendLine("\"Rate\" : \"" + CurrentRating.ToString() + "\"}]");

       context.Response.Write(jsonOutput);

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

 

}

 



ASP.Net Hosting

Recent Articles

For easy understanding, i have hard coded the average rating(CurrentRating) that should be returned to the caller after successful rating. In a real scenario, the current rating should be recorded to the database table and average rating for the item should be returned.

Points to consider

Ø       Since, the rating is sent from javascript(ajax call) you have to make sure if the request is already authenticated before rating if you want only authenticate user to rate. I have included the code for this checking, you can uncomment it.

Ø       In your stored procedure, include a condition to check if the user has already rated this item. Something like below,

if not exists(select rate from ArticleRating where id = @itemid and submittedby=@user)

Begin

//insert the rating

//select average rate for the itemid

End

 

Include a new javascript file called SimpleRating.js in _scripts folder to record the user rating to server through Ajax.

 

SimpleRating.js

/// <reference path="jquery-1.4.1.min.js" />

$(document).ready(function() {

 

    $("div.Rating").each(function() {

 

        var ItemID = $(this).children("INPUT[type=hidden]").val();

        var result = $(this).children("div[id=dvCurrentRate]");

 

        $(this).find("input[type=radio]").click(function() {

            var rate = $(this).val();

            RateIt(ItemID, rate, result);

            $(this).parent().find("input[type=radio]").attr("disabled", "disabled");

        });

 

        $(this).find("select").change(function() {           

            var rate = $(this).val();

            RateIt(ItemID, rate, result);

            $(this).attr("disabled", "disabled");

        });

 

    });

});

 

function RateIt(ItemID, rate, result) {

 

    $.getJSON("RateHandler.ashx?ItemID=" + ItemID + "&Rate=" + rate, function(output) {

        var avgRating = output[0].Rate;

        $(result).html(avgRating);

        alert("Successfully Rated!!");

    });

}

 

The above rating code will work even if we have more than one item in a page with rating control. Thus, we have used each() to find the rating control on the page.

 

    $("div.Rating").each(function()

 

That’s it! We are done with developing a simple rating control.

To test, include the user control in an aspx page like below and execute the application,

 

<%@ Register src="SimpleRating.ascx" tagname="SimpleRating" tagprefix="uc1" %>

 

Using RadioButtonList

    <uc1:SimpleRating ID="SimpleRating1" CurrentRating="4"

    MaxRate="5" ItemID="100"

    RatingControl="RadioButton" runat="server" /> 

Using DropDownList

<uc1:SimpleRating ID="SimpleRating2" CurrentRating="5" MaxRate="10" ItemID="101" RatingControl="DropDownList" runat="server" />

 

Download the source attached with this article and see it in action.

 

Downloads

Download Source 

 

Conclusion

As always, there will be always a source of improvement, hence download the code and change it or refine it to meet you need. You can have this article as a kick-start to develop a new rating control yourselves using jquery.  Please post your comments, suggestions to improve the above rating control to make it better.

 

Similar Articles
  • You can contribute to CodeDigest.Com:
    Article Feedback
    Title  
    Submitted By  
    Comment  
    Enter the verification number
     
    Comments