Click here to Skip to main content
Click here to Skip to main content

Yahoo! News Rotator using jQuery, CSS, JSON, and ASP.NET

By , 29 Dec 2009
 

Introduction

This Yahoo! news rotator control gives us the possibility of displaying several main news stories within the same area of a web page. News is taken apart to several pages in order to place them in a specified area. Each page also contains a couple of news items.

The control uses jQuery to:

  • Send a jQuery AJAX request to a web server to get news in JSON format
  • Bind data (news in the 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

The 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 the Open Source Json.NET library to make working with JSON formatted data in .NET easier. The key features include a flexible JSON serializer for quickly converting .NET classes to JSON and back again. Read more about the Json.NET library (code, sample, and documentation) here.

The 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 description (CSS/jQuery) by Soh Tanaka, here.

I also made some changes to the news rotator control by khaksari, available here.

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

Using the code

All you need to use this control is:

  • Reference the needed resources in your HTML page (.aspx page):
  • <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 the TopNews.ascx control in your .aspx page:
  • <%@ 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 the control by calling the JavaScript TopNews() function at the end of the control DOM. This function sends an AJAX request to the server, gets news in JSON format, binds news to the control, sets the control style to look nice after binding, and then rotates the news items.
  • <script type="text/javascript">
        new TopNews('#Container', 7,true,6000);
    </script>

TopNews function parameters

  • objRoot: The news rotator 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 instances of the control in the page without any worry of jQuery selection conflict.
  • newsCountPerPage: The number of news items in a page.
  • viewSubtitle: A boolean value that enables or disables the subtitle section of the control. The rest of the news titles show in the subtitle section randomly at the bottom of the current page.
  • Interval: The news rotation (slideshow) interval in milliseconds.

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 it an AJAX request.

//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:

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("Group 1", 
       this.ResolveUrl("~/img/news1.jpg"), 
       "http://www.yahoo.com", 
       this.ResolveUrl("~/img/news1.jpg"), 
       "This is a description about image 1 ...", 
       DateTime.Now.ToShortDateString()));
    lsttst.Add(new NewsItem("Group 2", 
       this.ResolveUrl("~/img/news2.jpg"), 
       "http://www.msn.com", 
       this.ResolveUrl("~/img/news2.jpg"), 
       "This is a description about image 2 ...", 
       DateTime.Now.ToShortDateString()));
    lsttst.Add(new NewsItem("Group 3", 
       this.ResolveUrl("~/img/news3.jpg"), 
       "http://www.msn.com", 
       this.ResolveUrl("~/img/news3.jpg"), 
       "This is a description about image 3 ...", 
       DateTime.Now.ToShortDateString()));
    lsttst.Add(new NewsItem("Group 4", 
       this.ResolveUrl("~/img/news4.jpg"), 
       "http://www.microsoft.com", 
       this.ResolveUrl("~/img/news4.jpg"), 
       "This is a description about image 4 ...", 
       DateTime.Now.ToShortDateString()));

    Response.ContentType = "application/json; charset=utf-8";
    Response.Write(
      Newtonsoft.Json.JavaScriptConvert.SerializeObject(lsttst));
    Response.End();
}

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

History

  • 20th December, 2009: Initial version.

License

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

About the Author

Arlen Navasartian
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionچطور روتیتوری داشته باشیم که تصاویر باینری را نشان دهدmemberghasempoor20 Oct '12 - 2:29 
GeneralMy vote of 1memberreza_boy6 Oct '12 - 5:15 
Questionyahoo news style with rollOver eventmemberhcc0011 May '12 - 17:42 
Questionthanksmembermuhamd yusuf15 Dec '11 - 0:34 
GeneralMy vote of 5memberkatiecat28 Oct '11 - 13:20 
GeneralHow can I change the images that are displayed ?memberMember 775503423 May '11 - 8:37 
Newsسلام Hellomemberho.kurd14 Apr '11 - 1:25 
Questionnice job but?memberamr rabie7 Apr '11 - 10:38 
AnswerRe: nice job but?memberArlen Navasartian18 Dec '12 - 10:59 
GeneralYour prevoius articlememberMichal Zubek6 Jul '10 - 5:14 
GeneralA question.memberTuliox28 Apr '10 - 8:52 
GeneralMore than 20 newsmemberkentex200021 Apr '10 - 13:52 
GeneralRe: More than 20 newsmemberArlen Navasartian22 Apr '10 - 5:32 
GeneralRe: More than 20 newsmemberkentex200022 Apr '10 - 23:23 
GeneralNews RotatormemberMember 42605887 Apr '10 - 4:08 
GeneralMy vote of 1memberarash.arash30 Jan '10 - 2:17 
GeneralGood jobmemberartin_77724 Jan '10 - 11:03 
Generalحج آرلنmemberarash.arash20 Jan '10 - 2:23 
GeneralRe: حج آرلنmemberArlen Navasartian20 Jan '10 - 12:02 
GeneralMy vote of 1memberarash.arash20 Jan '10 - 2:23 
Generalنظر باقریان بزرگهmembermoslem52219 Jan '10 - 23:53 
GeneralRe: نظر باقریان بزرگهmemberArlen Navasartian20 Jan '10 - 12:02 
Generalسلام آرلنmembermoslem52217 Jan '10 - 19:27 
GeneralRe: سلام آرلنmemberArlen Navasartian17 Jan '10 - 22:04 
QuestionCan this be done using WPF?memberAnkur_Mundhra11 Jan '10 - 22:26 
AnswerRe: Can this be done using WPF?memberArlen Navasartian12 Jan '10 - 9:34 
GeneralRe: Can this be done using WPF?memberAnkur_Mundhra12 Jan '10 - 17:30 
GeneralRe: Can this be done using WPF?memberArlen Navasartian13 Jan '10 - 10:53 
GeneralHimemberAnil Srivastava3 Jan '10 - 22:20 
GeneralRe: HimemberArlen Navasartian3 Jan '10 - 22:34 
GeneralRe: Hi [modified]memberAnil Srivastava3 Jan '10 - 23:57 
GeneralRe: HimemberAnil Srivastava7 Jan '10 - 23:04 
GeneralRe: HimemberArlen Navasartian8 Jan '10 - 12:43 
GeneralGood wook, but the slideshow does not workmemberjinboh3 Jan '10 - 10:19 
GeneralRe: Good wook, but the slideshow does not workmemberArlen Navasartian3 Jan '10 - 18:56 
GeneralRe: Good wook, but the slideshow does not workmemberjinboh5 Jan '10 - 3:26 
GeneralRe: Good wook, but the slideshow does not workmemberArlen Navasartian5 Jan '10 - 11:52 
GeneralRe: Good wook, but the slideshow does not workmemberkentex200011 Mar '10 - 23:33 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 30 Dec 2009
Article Copyright 2009 by Arlen Navasartian
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid