CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Rotate Text Link Advertisements Using jQuery in ASP.Net

By Satheesh Babu
Posted On Aug 19 14,2010
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 4
Category: jQuery
Print this article.

Rotate Text Link Advertisements Using jQuery in ASP.Net

 

There will be requirements where we need to rotate text ads or links in an ASP.Net page. For example, to provide features like news or stock ticker we need to basically rotate the news text or links at equal intervals.  In ASP.Net, there are various ways available through which we can rotate text links or advertisements. ASP.Net itself has packed with a control called AdRotator control which we can use to rotate ads. Read the below articles to know more about AdRotator control.

Using ADRotator Control in ASP.Net-Part 1

Using ADRotator Control in ASP.Net-Part 2

 

The main disadvantage of using AdRotator control is, it will change the advertisement only when there is a postback in the webpage.

 Moving forward, we will see how to rotate or change advertisements without using AdRotator control and postback by using jquery library.  For easy understanding(also to efficiently manage), we will store the ad information in SQL express database and will use JSON format to return the ads from database.

 

Steps

1.      With Visual Studio 2008, Create a sample Asp.Net website project.

2.      Choose a language in the Language Select box. I have selected C# as my language of choice. Name your website as per the need.

3.      Get the latest jQuery library from official jQuery.com site and integrate into your project. The following Faq’s will demonstrate how to integrate jQuery library into your project.

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?

4.      Create a new SQL express database(free database edition packed with visual studio) inside App_Data folder and create a table called Ads with necessary columns using “Server Explorer”.

Refer the below figure,

Rotate Text Link Advertisements or News Ticker control Using JQuery in ASP.Net

 

5.      In order to fetch the ads from database, we will create an HttpHandler which can read from the database and return the advertisements in JSON format. To create an HttpHandler, right click the project in your solution explorer and click “Add New Item”. Select “Generic Handler”. Rename it to GetAds.ashx and click OK. 
In ProcessRequest() event, we can read the ads from database and return it as a JSON string.

Refer the below code,

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

using System;

using System.Web;

using System.Data;

using System.Text;

using System.Data.SqlClient;

using System.Configuration;

using System.Web.Script.Serialization;

 

public class GetAds : IHttpHandler {

   

    public void ProcessRequest (HttpContext context) {

        string query = "SELECT * FROM [Ads]";

        DataTable dt = GetDt(query);

        StringBuilder strArticles = new StringBuilder();

 

        if (dt != null)

        {

            strArticles.Append("[");

            for (int i = 0; i < dt.Rows.Count; i++)

            {

                strArticles.Append("{");

                strArticles.Append("\"AdID\":\"" + dt.Rows[i]["AdID"].ToString() + "\",");

                strArticles.Append("\"AdTitle\":\"" + dt.Rows[i]["AdTitle"].ToString() + "\",");

                strArticles.Append("\"ADDesc\":\"" + dt.Rows[i]["ADDesc"].ToString() + "\",");

                strArticles.Append("\"Link\":\"" + dt.Rows[i]["Link"].ToString() + "\"");

                if (i != dt.Rows.Count - 1)

                {

                    strArticles.Append("},");

                }

            }

        }

        strArticles.Append("}");

        strArticles.Append("]");

        context.Response.ContentType = "application/json";

        context.Response.ContentEncoding = Encoding.UTF8;

        context.Response.Write(strArticles.ToString());

        context.Response.End();

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

 

    public DataTable GetDt(string query)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);

        SqlDataAdapter ada = new SqlDataAdapter(query, con);

        DataTable dt = new DataTable();

        ada.Fill(dt);

        return dt;

    }

 

}

 

Web.Config

       <connectionStrings>

              <add name="Sql" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>

       </connectionStrings>

6.      Now, we have created our HttpHandler which will return the ads when called. In order to display the ad in the webpage, we will define a html container(basically a div tag) in which we can rotate the text ads. In other words, you can place this div tag wherever you want to display the ads in your page. Open your Default.aspx, declare a div tag. Refer below,

<div id="dvADContainer">

<div id="dvAD"></div>

</div>

 

7.      Next, we will consume our HttpHandler from jquery and get the ads in JSON format.

For this we will use the getJSON() ajax method available in jQuery. To rotate the ads in equal interval, we will use the setInterval() method available in javascript. Refer the below code,




Rotate or Change Text advertisements from database

<script src="_scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        var i = 0;

        var adCount = 0;

        var ads;

        $(document).ready(function() {

            $.getJSON('GetAds.ashx', function(advs) {

                ads = advs;

                adCount = ads.length;

                RenderAds();

                setInterval(RenderAds, 2000);

            });

        });

 

        function RenderAds() {

            if (i < adCount) {

                var ad = "<a target=_new href=" + ads[i].Link + ">" + ads[i].AdTitle + "</a><br>" + ads[i].ADDesc;

                Showads(ad);

                i++;

            }

            else {

                i = 0;

                RenderAds();

            }

        }

 

        function Showads(str) {

            $("#dvAD").html(str);

        }

 

</script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <div id="dvADContainer">

        <div id="dvAD"></div>

        </div>

    </div>

 

The above code will rotate or change the ads in the div (dvAD) after every 2000ms(Change this to change the time interval of rotation). The function RenderAds() will construct the text ad from the JSON data and will populate it into the div whenever it is called from setInterval() method. You can change this method to change ad format displayed in the div tag.

That’s it! Execute the page and see it action.

 

Downloads

Download Source

 

Conclusion

There will be some common functionality which many of websites will share. For example, a news ticker, ad rotators, etc. There are many commercial softwares available in the market for these purposes. Using this article, one can implement a text link rotator easily ourselves. You can customize the above code to rotate image ads too with a little code change.

Download the code and see it in action!

Happy Coding!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
RE:Mr.
Hi Tsahi,
Thanks for your valuable feedback..i totally agree with you! It is always good to follow the standards mentioned by you..i didn't concentrate on these much as it is a example...!
Mr.
as you can see from the functions you used yourself, javascript uses camelCasing, and not PascalCasing. so RenderAds() should be renderAds() etc.

the html generated by RenderAds is not xhtml valid, and can be better even for html. attribute values should be enclosed in quotes, like so:
var ad = "<a target='_new' href='" + ads[i].Link + "'>" + ads[i].AdTitle + "</a><br>" + ads[i].ADDesc;


ASP DOT NET
Thanks for posting, I am first time this site and I impress that's really nice posting

Author
usauk-classifieds.com
Free Classifieds | Free Website Advertising for Marketing | Best Listing Site On the Web!
UsaUk-Classifieds.com is Web listing website, same as classified website, You can see ads on the web and easily publish your advertise absolutely free, Classifieds Website & WebListing Websites are generally same.