Click here to Skip to main content
15,867,835 members
Articles / Web Development / ASP.NET
Article

Create a News Rotator using jQuery, CSS, JSON and ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.67/5 (14 votes)
7 Sep 2009Ms-PL2 min read 91.1K   2.6K   60   11
An article on how to gather and show news stories in a slideshow
Image 1

Introduction

This news rotator control gives us the possibility of displaying several news stories within the same area of the web page. News is taken apart to several pages in order to place in a specified area. Each page also contains a couple of news items. By clicking on the page number at the bottom, it is possible to navigate between different pages and also by clicking on each news item of the page, it is possible to see its details. The stories slide into view. It also provides the auto next (slide show) feature, and transition styles.

It uses JQuery to:

  • Request JQuery Ajax Request to web server to get news in JSON format
  • Bind data (news in form of JSON) to HTML controls
  • Set the control style after data binding
  • Navigate between news
  • Interact with user
  • Change and set styles
  • Do JavaScript effects

News Rotator control uses ASP.NET to gather news from a news storage (for example database, XML file, RSS, ...), to cast news into a custom type (NewsItem), then convert a collection of newsItem objects to JSON format and send it to the client as a news rotator datasource.

This component uses open source Json.NET library to make working with JSON formatted data in .NET easier. Key features include a flexible JSON serializer for quickly converting .NET classes to JSON and back again. Read more about Json.NET library (code,sample and documentation) here.

News Rotator control uses the main idea of a jQuery Image Rotator sample. You can find out more about how to create an Image Rotator with its description (CSS/jQuery) By Soh Tanaka here.

This News Rotator control uses jQuery Cycle Plugin to rotate news, and it is a lightweight slideshow plugin. This plugin gives the developer a rich ability to rotate HTML controls on the page in the different rotation types. Read more about jQuery Cycle Plugin here.

Using the Code

All you need to use this control is:

  • Reference the needed resource to your HTML page (.aspx page):
    HTML
    <head>
        <script src='http://www.codeproject.com/jquery.js' 
    			type='text/javascript'></script>
        <script src='http://www.codeproject.com/jquery.cycle.all.min.js' 
    			type='text/javascript'></script>
        <script src='http://www.codeproject.com/TopNews.js' 
    			type='text/javascript'></script>
        <link href='http://www.codeproject.com/TopNews.css' 
    			rel='stylesheet' type='text/css' />
    </head>
  • Register and embed TopNews.ascx control to your .aspx page:
    HTML
    <%@ Register Src="~/TopNews.ascx" TagName="TopNews" TagPrefix="ctrl" %>
    <body>
        <form id="form1" runat="server">
        <div>
            <ctrl:TopNews runat="server" id="TopNews1" />
        </div>
        </form>
    </body>
  • Start control through calling JavaScript TopNews() function at the end of control DOM. This function sends an Ajax request to the server, gets news in JSON format, binds news to the control, sets control style to look nice after binding and then rotates news.
    HTML
    <script type="text/javascript">
        new TopNews('#Container', 7,true,6000);
    </script>
    TopNews function parameters:
    parameter 1(objRoot): newsRotator control container (a jquery selector),
    the control uses this parameter as a prefix (root object) of every
    jquery selector inside the control.this prefix helps to have multiple instance
    of control in the page without any worry of jquery selection conflict.
    parameter 2(newsCountPerPage): number of news items in a page.
    parameter 3(viewSubtitle): a boolean value makes subtitle section
    of the control enable or disable. the rest of the news titles shows
    in the subtitle section randomly at the bottom of the current page.
    parameter 4(Interval): news rotation (slideshow) interval in millisecond.
  • It also needs a server side mechanism to gather news, convert news to JSON format and send them to the client.

    In the client, we use jquery to call a server method sending that an Ajax request.

    C#
    //call ASP.NET page method asynchronous (send and recives data in JSON format)
    PageMethod: function(fn, paramArray, successFn, errorFn) {
        var pagePath = window.location.pathname;
        var that = this;
        //Call the page method
        $.ajax({
            type: "POST",
            url: pagePath + "?Callback=" + fn,
            contentType: "application/json; charset=utf-8",
            data: paramArray,
            dataType: "json",
            //that is a reference to the object calling this callback method
            success: function(res) { successFn(res, that) },
            error: errorFn
        });
    }
    

    And at the server side, we have this:

    C#
    protected void Page_Load(object sender, EventArgs e)
    {
        // *** Route to the Page level callback 'handler'
        this.HandleCallbacks();
    }
    
    // Callback routing
    public void HandleCallbacks()
    {
        if (string.IsNullOrEmpty(Request.Params["Callback"]))
            return;
    
        // *** We have an action try and match it to a handler
        switch (Request.Params["Callback"])
        {
            case "fetchAllNews":
                this.FetchAllNews();
                break;
        }
    
        Response.StatusCode = 500;
        Response.Write("Invalid Callback Method");
        Response.End();
    }
    
    public void FetchAllNews()
    {
        List<NewsItem> lsttst = new List<NewsItem>();
        lsttst.Add(new NewsItem("Environment of Australia",
        this.ResolveUrl("~/img/news1.jpg"),
        this.ResolveUrl("~/img/news1_thumb.jpg"),
        "Australia has a rich variety of endemic legume
        species that thrive in nutrient-poor soils because
        of their symbiosis with rhizobia bacteria and mycorrhizal fungi",
        DateTime.Now.ToShortDateString()));
        lsttst.Add(new NewsItem("Economy of Australia",
        this.ResolveUrl("~/img/news2.jpg"),
        this.ResolveUrl("~/img/news2_thumb.jpg"),
        "The Australian dollar is the currency of the
        Commonwealth of Australia, including Christmas Island,
        Cocos (Keeling) Islands, and Norfolk Island",
        DateTime.Now.ToShortDateString()));
        lsttst.Add(new NewsItem("Demographics of Australia and
        Immigration to Australia", this.ResolveUrl("~/img/news3.jpg"),
        this.ResolveUrl("~/img/news3_thumb.jpg"),
        "Most of the estimated 21.8 million Australians are
        descended from colonial-era settlers and post-Federation
        immigrants from Europe", DateTime.Now.ToShortDateString()));
        lsttst.Add(new NewsItem("Religion in Australia",
        this.ResolveUrl("~/img/news4.jpg"),
        this.ResolveUrl("~/img/news4_thumb.jpg"),
        "Australia has no state religion. In the 2006 census,
        64% of Australians were listed as Christian of
        any denomination, including 26% as Roman Catholic and
        19% as Anglican", DateTime.Now.ToShortDateString()));
        lsttst.Add(new NewsItem("Education in Australia",
        this.ResolveUrl("~/img/news5.jpg"),
        this.ResolveUrl("~/img/news5_thumb.jpg"),
        "School attendance is compulsory throughout Australia.
        In most Australian States at 5–6 years of age all children
        receive 11 years of compulsory education",
        DateTime.Now.ToShortDateString()));
    
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write(JavaScriptConvert.SerializeObject(lsttst));
        Response.End();
    }
    

The source code contains the needed comments to illustrate more details about how this control works.

History

  • 6th September, 2009: Initial version

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Software Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questiongod slider Pin
Member 348097615-Aug-12 13:01
Member 348097615-Aug-12 13:01 
Generalnice job but! Pin
amr rabie7-Apr-11 10:04
amr rabie7-Apr-11 10:04 
GeneralDoes not work on IE7 Pin
Michal Zubek5-Jul-10 23:44
Michal Zubek5-Jul-10 23:44 
GeneralAlert Error ! Pin
Despa2212-Jun-10 22:27
Despa2212-Jun-10 22:27 
QuestionI need Help ! Pin
kimlong008`21-May-10 15:20
kimlong008`21-May-10 15:20 
Generalnot work Pin
Member 343652518-May-10 3:28
Member 343652518-May-10 3:28 
GeneralQuestion. Pin
Tuliox20-Apr-10 8:02
Tuliox20-Apr-10 8:02 
Generalnice job Pin
Arlen Navasartian15-Jan-10 23:20
Arlen Navasartian15-Jan-10 23:20 
Generalits nice but something is missing Pin
o4ovais14-Sep-09 20:07
o4ovais14-Sep-09 20:07 
Generalnice Pin
Tammam Koujan8-Sep-09 13:56
professionalTammam Koujan8-Sep-09 13:56 
nice job
thank you
Generalnice job! Pin
Masoud DaneshPour8-Sep-09 9:31
Masoud DaneshPour8-Sep-09 9:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.