DotNetCurry Logo

Rotate Ads using jQuery and ASP.NET AdRotator Control

Posted by: Suprotim Agarwal , on 9/6/2010, in Category jQuery and ASP.NET
Views: 110207
Abstract: The ASP.NET AdRotator control is a useful control to randomly display advertisements on a webpage. However the ads in the adrotator control are rotated only when the user refreshes the page. In this article, we will use a single line of jQuery code to rotate ads using the adrotator control, at regular intervals and without refreshing the page.
The ASP.NET AdRotator control is a useful control to randomly display advertisements on a webpage. However the ads in the adrotator control are rotated only when the user refreshes the page. In this article, we will use a single line of jQuery code to rotate ads using the adrotator control, at regular intervals and without refreshing the page.
Note: If you are doing jQuery development with ASP.NET Controls, you may find my EBook called 51 Recipes with jQuery and ASP.NET Controls useful.
We will first create a simple adrotator control and then add some jQuery logic to it.
Step 1: Open VS 2008/2010. Click File > New > Website. Choose ASP.NET Website from the list of installed template, choose target platform as .NET Framework 2.0/3.5/4.0, choose the desired language and enter the location where you would like to store the website on your FileSystem (C:\VS 2010 Projects\AdRotatorjQuery. After typing the location, click OK.
Step 2: Now create some banners images to test out the adrotator functionality and drop them in the images folder of your project. I have designed three 200 * 200 png banners (adone, adtwo and adthree). You can find the images in the source code of this article.
Step 3: The AdRotator control can retrieve the list of advertisements from either a XML file or from the database. To keep things simple, I will be using an XML file. So the next step is to create the advertisement file. I prefer to create this file in the App_Data folder to take advantage of the security this folder provides. To do so, right click the App_Data folder > Add New Item > ‘XML File’ > Rename it to ads.xml and click Add. Now add the following contents to the ‘ads.xml’ file:
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
 <Ad>
    <ImageUrl>~/images/adone.png</ImageUrl>  
    <NavigateUrl>http://www.dotnetcurry.com</NavigateUrl>
    <AlternateText>DotNetCurry Home Page</AlternateText>
    <Impressions>30</Impressions>
    <Keyword>small</Keyword>
 </Ad>
 <Ad>
    <ImageUrl>~/images/adtwo.png</ImageUrl>
    <NavigateUrl>http://www.sqlservercurry.com</NavigateUrl>
    <AlternateText>SQLServerCurry Home Page</AlternateText>
    <Impressions>30</Impressions>
    <Keyword>small</Keyword>
 </Ad>
 <Ad>
    <ImageUrl>~/images/adthree.png</ImageUrl>
    <NavigateUrl>http://www.devcurry.com</NavigateUrl>
    <AlternateText>DevCurry Home Page</AlternateText>
    <Impressions>40</Impressions>
    <Keyword>small</Keyword>
 </Ad
</Advertisements>
 
Step 4: Our next step is to add the AdRotator control and bind it to the advertisement file. Drag and drop an AdRotator control from the toolbox to the Default.aspx. To bind the AdRotator to our XML file, we will make use of the ‘AdvertisementFile’ property of the AdRotator control as shown below:
<div class="ads">
        <asp:AdRotator
        id="adr"
        AdvertisementFile="~/App_Data/Ads.xml"
        KeywordFilter="small"
        Runat="server" />
</div>
 
Note: The ‘KeywordFilter’ property enables you to filter advertisement using a keyword. If your Advertisement file contains different kinds of ads (banner, leaderboard, skyscraper etc.), you can use this property to filter out different ads on different sections of the page. If you observe, the ads.xml file also contains a property called ‘Keyword’ which binds that ad with the AdRotator that contains the same KeywordFilter, in our case ‘small’.
So far, we have a fully functional adrotator control which displays a new ad, when you refresh the page. Let’s see how we can use jQuery to rotate ads without page refresh.
 
Using jQuery to Rotate ads in the ASP.NET AdRotator without Refreshing the Page
 
Step 5: Time for some jQuery magic! Add the following jQuery code in the <head> section of the page
<head runat="server">
<title>Rotating ads using ASP.NET AdRotator and jQuery</title>
<script type="text/javascript"
    src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        setInterval(function () {
            $("#adr").load(location.href + " #adr", "" + Math.random() + "");
        }, 4000);
    });
</script>
</head>
 
In the code shown above, we are doing a partial page update using jQuery. Using the setInterval function, we call the jQuery load() api, to fetch data after every 4 seconds.
The jQuery load() function allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
That’s what we are doing in this piece of code. Observe the space before “ #adr” in the load function, which turns it into a jQuery selector.
$("#adr").load(location.href + " #adr", "" + Math.random() + "");
 
In an ASP.NET Master page, use this piece of code
$('[id$=adr]').load(location.href + " #[id$=adr]", "" + Math.random() + "");
 
When this method executes, jQuery parses the returned document to find the #adr element  and inserts the element with its new content, discarding the rest of the document. That’s how we see a new ad at regular intervals.
Note: We have used Math.random() here so that IE does not treat it as similar requests and cache it. If we do not do this, you will never see a new image loading in IE. Using Firebug, here’s what each request looks like.
image_2
Here’s an output of what the page will look like. I have printed the current time in a label control to be sure that the entire page is not being refreshed.
AdRotator
You can see a Live Demo. The example has been tested on the latest browsers including IE8, Firefox 3.6 and Chrome 5.
The entire source code of this article can be downloaded over here
If you are doing ASP.NET with jQuery development, check out my EBook called 51 Recipes with jQuery and ASP.NET Controls.
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Burt C on Sunday, September 12, 2010 12:32 AM
Nice use of jquery. With the AJAX toolkit, the same thing would consume more bytes and crazy markups!
Comment posted by Antonio on Wednesday, December 1, 2010 12:35 PM
How can I implement this using images stored in a database?
Thanks
Comment posted by Reid on Monday, January 24, 2011 9:33 PM
I'm finding this doesn't work correctly in Firefox 3.6.  The images change but the url loaded on the initial page load remains, causing the user to be sent to the wrong url.  Anyone else have this problem?
Comment posted by Mike on Saturday, February 12, 2011 6:28 PM
This article is brief, which is GOOD, but it is poorly written, which is bad. The author does not take the time and make the effort to me "complete and specific" regarding such things as clarifying the items that require customization and including all the tags. Too bad.
Comment posted by Suprotim Agarwal on Tuesday, February 15, 2011 3:18 AM
Mike: Which part of the article is not 'complete and specific'?
Comment posted by Pushkar on Wednesday, March 9, 2011 11:28 PM
Hi Supromit Brother.
Your recipes using jQuery for adRotator is amazing.
But i have one problem for this article.
I have put the same code as shown here.
But page load again when image is changed.
I am not using XML ,i fetched the records from the DB.

Thanks
Pushkar
Comment posted by Suman Chanda on Monday, April 4, 2011 3:02 PM
Very nice article, awesome use of jquery
Comment posted by Vamshi Krishna on Friday, April 8, 2011 2:20 PM
Hi Suprotim, im a newbie to JQuery. could you tell me how i can use the code if data is from DB (not XML).
Comment posted by Suprotim Agarwal on Sunday, April 10, 2011 4:30 AM
Vamshi: You will have to use ajax and call a service that pulls value from the database. Check my articles here to get an idea:

http://www.devcurry.com/2011/01/jquery-ajax-aspnet-json-web-service.html

http://www.dotnetcurry.com/ShowArticle.aspx?ID=454
Comment posted by Muruga on Tuesday, June 7, 2011 12:54 AM
same code i tried but i am getting the result.
ERROR:"This XML file does not appear to have any style information associated with it. The document tree is shown below."
this is the error i am getting when i thought to run
Comment posted by Jim on Saturday, October 1, 2011 4:25 PM
I have inserted this code in my Master page, and now the AdRotator control is rotating automatically as I wanted.  However, an associated Hyperlink control is not getting updated when this happens.

The Hyperlink control's Text property is updated in a function called by the OnAdCreated event of the AdRotator.  That function sets the Text property to the current ad's Caption from the XML advertisement file.  Apparently the OnAdCreated event is not firing when the AdRotator changes ads, because the caption from the first ad displayed remains in place as new ads are displayed in the AdRotator.  The caption only changes when the entire page is refreshed.  How can I make the caption change automatically along with the content of the AdRotator?
Comment posted by Ankit Singh on Wednesday, January 11, 2012 2:06 AM
Hi,

I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of AdRotator Control in Asp.Net and it helped me a lot. Thanks for sharing with us. Check out this link too its also having nice post with wonderful explanation on AdRotator control....

http://mindstick.com/Articles/8766b284-d4bf-4ae1-891f-03f74d2a50b8/?AdRotator%20Control%20in%20ASP.Net

Thank you very much for your precious post!!
Comment posted by Megha Jalan on Thursday, September 13, 2012 12:53 AM
How can we implement "adrotator" in ASP.Net MVC3
Comment posted by Freddy Poma on Thursday, May 23, 2013 12:49 AM
For MasterPage use:
$('[id$=adr]').load(location.href + " id$=adr]", "" + Math.random() + "");

Besides

$('[id$=adr]').load(location.href + " #[id$=adr]", "" + Math.random() + "");

Thanks for the code.
Comment posted by Mindy on Monday, June 24, 2013 3:21 PM
Awesome article. My ad roator is in an user control and it is used within a master template. The ad did not rotate, not sure how to work around it. Your help will be greatly appreciated!

Thanks
Comment posted by RK on Friday, December 27, 2013 5:59 AM
nice 1. But i have found another example for the same please visit http://www.etechpulse.com/2013/05/adrotator-how-to-rotate-advertisements.html
Comment posted by anandu on Tuesday, June 10, 2014 11:15 AM
how to dicrement database id(stock) from the textbox text number