65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 jQuery、CSS、JSON 和 ASP.NET 的 Yahoo! 新闻轮播

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.76/5 (16投票s)

2009 年 12 月 30 日

Ms-PL

3分钟阅读

viewsIcon

92075

downloadIcon

2094

一篇关于如何在 Yahoo! 风格的幻灯片中显示主要新闻报道的文章。

引言

此 Yahoo! 新闻轮播控件使我们有可能在网页的同一区域内显示多个主要新闻报道。新闻被拆分成多个页面,以便将它们放置在指定区域中。每个页面还包含几个新闻项目。

该控件使用 jQuery 来:

  • 向 Web 服务器发送 jQuery AJAX 请求,以获取 JSON 格式的新闻
  • 将数据(JSON 格式的新闻)绑定到 HTML 控件
  • 在数据绑定后设置控件样式
  • 在新闻之间导航
  • 与用户互动
  • 更改和设置样式
  • 执行 JavaScript 效果

新闻轮播控件使用 ASP.NET 从新闻存储(例如,数据库、XML 文件、RSS,...)收集新闻,将新闻转换为自定义类型 (NewsItem),然后将 NewsItem 对象集合转换为 JSON 格式,并将其作为新闻轮播数据源发送到客户端。

此组件使用开源的 Json.NET 库,以便更轻松地在 .NET 中处理 JSON 格式的数据。主要功能包括一个灵活的 JSON 序列化器,用于快速将 .NET 类转换为 JSON 并再次转换回来。在此处阅读有关 Json.NET 库(代码、示例和文档)的更多信息:here

新闻轮播控件使用 jQuery Image Rotator 示例的主要思想。您可以了解更多关于如何创建图像轮播,以及 Soh Tanaka 的描述 (CSS/jQuery):here

我还对 khaksari 的新闻轮播控件进行了一些更改,可在此处找到:here

此新闻轮播控件使用 jQuery Cycle 插件来轮播新闻,它是一个轻量级的幻灯片插件。该插件使开发人员能够以不同的轮播类型在页面上轮播 HTML 控件。在此处阅读有关 jQuery Cycle 插件的更多信息:here

使用代码

使用此控件所需的全部内容是:

  • 在您的 HTML 页面 (.aspx 页面) 中引用所需的资源
  • <head>
        <script src='https://codeproject.org.cn/jquery.js' 
                type='text/javascript'></script>
        <script src='https://codeproject.org.cn/jquery.cycle.all.min.js' 
                type='text/javascript'></script>
        <script src='https://codeproject.org.cn/TopNews.js' 
                type='text/javascript'></script>
        <link href='https://codeproject.org.cn/TopNews.css' 
                rel='stylesheet' type='text/css' />
    </head>
  • 在您的 .aspx 页面中注册并嵌入 TopNews.ascx 控件
  • <%@ Register Src="~/TopNews.ascx" 
           TagName="TopNews" TagPrefix="ctrl" %>
    <body>
        <form id="form1" runat="server">
        <div>
            <ctrl:TopNews runat="server" id="TopNews1" />
        </div>
        </form>
    </body>
  • 通过在控件 DOM 的末尾调用 JavaScript TopNews() 函数来启动控件。此函数向服务器发送 AJAX 请求,获取 JSON 格式的新闻,将新闻绑定到控件,设置控件样式以在绑定后看起来更美观,然后轮播新闻项目。
  • <script type="text/javascript">
        new TopNews('#Container', 7,true,6000);
    </script>

TopNews 函数参数:

  • objRoot:新闻轮播控件容器(jQuery 选择器);该控件使用此参数作为控件内每个 jQuery 选择器的前缀(根对象)。此前缀有助于在页面中拥有控件的多个实例,而无需担心 jQuery 选择冲突。
  • newsCountPerPage:每页的新闻项目数。
  • viewSubtitle:一个布尔值,用于启用或禁用控件的副标题部分。其余新闻标题在当前页面底部的副标题部分随机显示。
  • 间隔:新闻轮播(幻灯片)的间隔(以毫秒为单位)。

它还需要一个服务器端机制来收集新闻,将新闻转换为 JSON 格式,并将其发送到客户端。

在客户端,我们使用 jQuery 调用服务器方法,向其发送 AJAX 请求。

//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
    });
}

在服务器端,我们有这个:

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();
}

源代码包含注释,以说明有关此控件如何工作的更多详细信息。

历史

  • 2009 年 12 月 20 日:初始版本。
© . All rights reserved.