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

AJAX DataGrid

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.50/5 (2投票s)

2007年12月5日

CPOL

3分钟阅读

viewsIcon

43688

downloadIcon

319

本文展示了如何使用 AJAX 更新 DataGrid(DataView)控件中的数据。

Screenshot - AjaxDataGrid

引言

本文介绍了如何通过 AJAX 更新 ASP.NET 2.0 DataView 控件中的数据。

问题描述

假设有一个电子商务应用程序,允许客户在网上购买产品。每次销售完成后,剩余产品的数量都会更新。我们还假设有必要实时监控这些数量(这在销售量大且需要频繁订购所需产品的情况下可能是必需的)。在这种情况下,拥有一个包含所需产品和库存单位的网页将会很有用,该网页将通过异步调用在设定的时间间隔(例如 5 秒)内进行更新。当我接到开发类似页面的请求时,我在互联网上花了许多时间寻找任何可行的示例来给我一些关于如何做到的想法,但都没有成功。大多数文章都说得很好听,但没有代码行;其他文章提供的示例却无法正常工作。所以,过了一段时间,我提出了自己的方法来实现这一点,我希望本文能帮助到那些试图理解 AJAX 的人。

背景

该示例使用了 Northwind 数据库中 Products 表的数据。该方法基于使用 XmlHttpRequest 对象,通过该对象,你可以使用 JavaScript 向服务器发送/从服务器获取任何数据。要实现 AJAX 调用,实际上需要有两个网页:一个对最终用户可见,另一个实际生成第一个网页所需的内容。第一个页面通过 JavaScript 中实现的 XmpHttpRequest 调用第二个页面。

使用代码

在下面的示例中,我们将有两个网页

  • Default.aspx - 将显示给最终用户的页面
  • DataGrid.aspx - 将每 5 秒更新一次,为 Default.aspx 页面提供内容。

正如所说,该示例使用了 Northwind 数据库,其连接字符串在 web.config 文件中提供。

<appSettings>
    <add key="DSN" 
      value="server=localhost;Integrated Security=SSPI;database=Northwind" />
</appSettings>

业务逻辑层位于 App_Code\BLL 子文件夹中,包含 ProductsBLL 类,该类有一个 GetProducts() 方法,该方法实际上从 Northwind 数据库的 Products 表中返回 CategoryId=1 的所有产品。

/// <summary>
/// Summary description for ProductsBLL 
/// </summary>public class ProductsBLL 
{
    public static void GetProducts(DataSet ds) 
    { 
        string sqlString = "SELECT ProductId, ProductName, " + 
                           "QuantityPerUnit UnitPrice, UnitsInStock " + 
                           "FROM Products WHERE CategoryId=1 " + 
                           "order by ProductName"; 
        SqlHelper.FillDataset(SqlHelper.connection(), 
                              CommandType.Text, sqlString, ds, 
                              new string[] { "Products" }); 
    } 
}

上述方法使用了位于 App_Code\DAL 子文件夹中的数据访问层FillDataset 方法,其中包含一个 SqlHelper 类,该类包含一组数据访问方法。SqlHelper 类是基于开源应用程序块数据访问类创建的,可以成功用于访问 SQL Server 数据库中的数据。

现在我们来看一下 DataGrid.aspx 网页。该页面包含 Label1 控件和 GridView 控件 gvGrid,它们都在 Page_Load 事件中填充。DataView 控件用来自产品数据集的数据填充,而 Label1.Text 则用当前的日期/时间进行更新。

protected void Page_Load(object sender, EventArgs e) 
{ 
    DataSet ds = new DataSet(); 
    ProductsBLL.GetProducts(ds); 
    gvGrid.DataSource = ds; 
    gvGrid.DataBind(); 

    Label1.Text = "Units in Stock for: " + DateTime.Now.ToString(); 
}

Default.aspx 页面包含一个 <div> 部分,其 id="GridSection",以及一个 Input 按钮 btnGet,该按钮在 Click 事件上调用 AJAX JavaScript 函数 doCall()。通过 AJAX 调用接收到的数据将被放置在 <div> 元素内。

<input id="btnGet" type="button" value="Get Data" onclick="doCall()"/> 
.
.
.
<div id= "GridSection">

</div>

现在,我们来看一下实际上完成所有工作的 Ajax.js JavaScript。

// Creating the instance of the XmlHttpRequest 
// This is done differently for different browsers
// Branch for native XMLHttpRequest object 

var client=null; 
if (window.XMLHttpRequest) 
{ 
    client = new XMLHttpRequest(); 
} 
// Branch for IE/Windows ActiveX version 
else if (window.ActiveXObject) 
{ 
    client = new ActiveXObject("Microsoft.XMLHTTP"); 
} 

//Sending information to server 
function doCall() 
{ 
    try 
    { 
        //callBack; 

        var url="DataGrid.aspx" 
        url=url+'?d='+Date(); 
        client.open("GET", url); 
        client.onreadystatechange = callBack; 
        client.send(); 
    } 
    catch(ex) 
    { 
        alert(ex.message); 
    } 
 
    setTimeout('doCall()', 5000); //5 sec 

} 
 
//Waiting and processing server response 

function callBack(response) 
{ 
    try 
    { 
        if(client.readyState == 4 && client.status == 200) 
        { 
            xmlDocument = new ActiveXObject('Microsoft.XMLDOM'); 
            xmlDocument.async = false; 
 
            //The responseText is loaded into XML document 
            xmlDocument.loadXML(client.responseText); 
            //Get the node
            vargridNode=xmlDocument.selectSingleNode(
              '/html/body/form/div[@id="Grid"]'); 
 
            //Replace innerHTML of the default.aspx page with the response node.xml 
            document.getElementById("GridSection").innerHTML=gridNode.xml; 
        } 
    } 
    catch(ex) 
    { 
        alert(ex.message); 
    } 
}

要测试该示例,请打开 Default.aspx 页面,然后单击“Get Data”按钮。页面将使用来自 Products 表的产品数据填充 DataViewDataView 中的数据每 5 秒刷新一次。要测试此功能,请打开 Northwind 数据库的 Products 表,并更改 CategoryId=1 的某个产品的 UnitsInStock 字段的数据。Default.aspx 网页上的数据将在 5 秒后更改,而无需回发。

关注点

使用上述技术,可以异步更新页面中包含不同数据的各个部分,这在使用需要不只是在用户回发页面时,而是在特定时间间隔刷新给用户的数据时非常有用。

历史

不适用。

© . All rights reserved.