Monday, March 14, 2011

Rotate Ads using jQuery and ASP.NET AdRotator Control

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.mywebsite.com</NavigateUrl>
    <AlternateText> mywebsite Home Page</AlternateText>
    <Impressions>30</Impressions>
    <Keyword>small</Keyword>
 </Ad>
 <Ad>
    <ImageUrl>~/images/adtwo.png</ImageUrl>
    <NavigateUrl>http://www.mywebsite.com</NavigateUrl>
    <AlternateText> mywebsite Home Page</AlternateText>
    <Impressions>30</Impressions>
    <Keyword>small</Keyword>
 </Ad>
 <Ad>
    <ImageUrl>~/images/adthree.png</ImageUrl>
    <NavigateUrl>http://www.mywebsite.com</NavigateUrl>
    <AlternateText> mywebsite 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.

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.

No comments:

Popular Posts