Star User Rating Control in Asp.Net Using Jquery

With a little CSS, a tiny amount of jQuery and a little ingenuity you can easily create a reusable rating control in using jquery.

The Basics

For the CSS I decided there was no reason to re-invent the wheel, so I used Komodo Media’s CSS Star Rating Part Duex for the styles, although I did rename them (only because I prefer short, simple class names).

Here’s the basic HTML structure of the rating system:

And here are the styles:

And, here’s the star image:

If you add what we have here to a page and view it in the browser, you’ll see a nice rating system. The current class represents the selected rating. That will show the lighter star, then hovering over the stars will show the darker star, otherwise the star outline will appear.

This looks quite nice and works great. However, there’s no real practical application to it. Clicking on one of the stars does nothing. Even if it did there is currently no way to send it back to the server, say, to update a rating field stored in a database field.

The Server Control

There are several ways to go about making this function. I chose to use an Asp.Net RadioButtonList with five ListItems with the appropriate values. Here’s the code:

Again, pretty simple. I always create a .hidden class in my stylesheet where I set the display: none. You cannot use Visible=”False” because the control will not be accessible via JavaScript because it won’t actually render to the page.

The jQuery

Now, before we make this a control, here’s the basics of the jQuery. We need to add a click event to the <a> tags inside the rating to do two things. First, remove the .current class from all the other <a> tags and then add the .current class back to the selected <a>.

Here’s the code for that:

Not only does the <a> tag need the .current class added to it, the correct radiobutton needs checked. In the same click function we’ll do that:

That’s all there is to it. Now view this in the browser, click on the rating and the appropriate radio button will select. Of course if you have the RadioButtonList hidden you won’t see it, but you can un-hide it just to see it in action.

Now we can set the selected value of the RadioButtonList through server code and we can get the selected value on a post back. Only problem is that when setting the value from code-behind, setting the current star value requires more work. We would either have to make the <a> tags HyperLink controls or create the entire star rating HTML from code-behind and then add it to the page.

Or…we could make a reusable CompositeControl that we could simply drop on a page and it would do all the work for us.

The StarRating User Control

First off, we need to create a class. I called my StarRating under the namespace TD.Controls. The reason for the namespace is that I will be referencing this control like we would a regular ascx user control on the page. I decided to inherit the System.Web.UI.Control. This gives us all the properties and methods available for a generic web control. Here’s what we have so far. Notice you’ll need to add the System.Web, System.Web.UI, System.Web.UI.WebControls, System.Web.UI.HtmlControls, System.Text, and System.ComponentModel namespaces.

Adding Control Properties

Now that we have the framework  for this control, let’s add some public properties to allow for some customization as well as a property to hold the actual rating value.

I’ve set the DefaultValue of the Rating property to -1 mainly because I prefer to set int values to -1 rather than 0 for a default value. You may notice that the get method of the Rating property calls the base method EnsureChildControls, that ensures that the child controls (the RadioButtonList we’ll be creating later) exists. And if the RadioButtonList has a selected item it will return the SelectedValue. And since -1 is the default value the star rating (and associated RadioButtonList) will be in it’s initial state.

Read Also:  How to install non-free drivers during Debian Installation

All of the other properties deal with the layout and styling of the control. The properties for setting the css classes for each item will just give you an option if you don’t like my class names. I won’t be offended if you change them.

Now that all the properties are set up we can start building the actual control. Since the main controller will be RadioButtonList we will declare that as out as a private variable. Then we need to override the System.Web.UI.Control method CreateChildControls(). In this method we will instantiate (just a fancy word for create) our RadioButtonList. Once the RadioButtonList is created we’ll add the ListItems for the values 1-50. I’ll also add an ID so we can access it via jQuery.

And, I really can’t stand that by default RadioButtonLists are rendered inside a table, so I’m changing the RepeatLayout to Flow…I don’t care for that much either, but it’s better than a table. Lastly, I’ve added a style attribute to hide the RadioButtonList (remember, if you set it to Visible=False you won’t be able to access it from JavaScript).

CreateChildControls method

Once the RadioButtonList is created and the items are added, the SelectedValue of the RadioButtonList needs set if the Rating is not -1. Finally, the RadioButtonList needs added to the Control Collection of the control.

Render Method

Now that the RadioButtonList has been created we need to render our StarRating control to the page. We do this by overriding the base Render(HtmlTextWriter writer) method.

The first thing is to check whether WrapWithDiv is true and render the outer div accordingly. Then add the DivCssClass to the outer div if set. After that we can render our RadioButtonList. The rest of the method creates the HTML <ul> to hold the visual star rating.

Each time a new <li> is created it checks to see if that value equals the Rating property. If it does it will add the selectedCssClass property to keep everything in sync. We’re almost there! Oh, by the way, notice I’ve set the href of each <a> to “javascript:;”…the reason being that if you set it to # the link actually does something. By setting it to javascript:; it will do nothing.

Now the jQuery

One thing we have to account for when writing our javascript is that we need the ability to add multiple StarRating controls to a page. We need to make sure that each one will work independently. This is why I set the IDs of both the RadioButtonList and the HtmlGenericControl to hold the <ul>. I used the current controls ClientID as a prefix because the ClientID will be unique to each instance of the control whereas just using the ID would not be unique and not only cause the StarRating control not to function properly, it would also give multiple elements the same ID which is a no-no.

To add the jQuery I’ll be using the ClientScriptManager’s RegisterStartupScript method. I’ll add this to a PageLoad method. To do this I must first add a Load method to the control. I also added an Init event to call the EnsureChildControls(). Not completely sure if this is necessary, but it doesn’t hurt anything either.

To add these methods to add a Constructor for the control.

Now here are the _Init & _Load methods.

Again, since there could be multiple controls on the same page we need to give the startup script a unique key as well. Then we check to see if the script has been added or not. If not we add it.

There are other ways you could build the JavaScript, but I chose a StringBuilder. First thing is I create a unique variable to hold the current control. Then I add a click event to each of the <a> tags inside the <ul>. Inside that click event I set a variable to hold the <a> that was clicked an get the html inside the <a> which should just be the numbers 1-5. I reset all the radio buttons inside the  RadioButtonList to be un-checked.

Then I find the corresponding radio button with the value of the html of the <a> and set it’s checked attribute to checked. All that remains is to remove the selectedCssClass from all the other <a> tags and then add the class back to the one that was clicked. That’s pretty much it.

Adding the control to a page

To add our new control to a page you can reference it in the Page directives like you would a user control, except you wouldn’t provide the Src attribute, you would provide the TD.Controls as the NameSpace. You also don’t need to provide a TagName. All the controls within the provided namespace will be available with the same TagPrefix.

Then on the page where you want the rating,

You could also reference the control in the web.config Pages section. This would make it available on every page without having to add the Page Directive.

Oh, one last important thing. Make sure the styles are set up in your stylesheet and the star.gif image is in your images directory (or wherever your stylesheet says it is)!

View your page in the browser and you should see 5 empty stars. Hover over a star and see them magically appear. Click on one and it should stay selected.

Just to make sure it works with more than one control on a page, let’s add another and explicitly set the rating.

Now if you view your page in the browser you should see two star ratings, 1 blank and one with 3.

One last thing, let’s add a Button and Literal control and see if it posts back.


The Code-Behind

There you have it! You now have a completely reusable and customizable star rating control! Enjoy!

Oops, almost forgot. The control will require you are referencing jQuery and have a ScriptManager on your page (or Master Page).

Leave a Reply

Your email address will not be published. Required fields are marked *