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

在生成应用程序中实现 AJAX 代码自定义

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.15/5 (4投票s)

2008年4月26日

CPOL

7分钟阅读

viewsIcon

13916

本文演示了在使用 Iron Speed Designer V4.0 生成的应用程序中添加 AJAX 代码自定义是多么容易。

引言

Iron Speed Designer 版本 4.0 可生成支持 AJAX 的应用程序,并为 .NET Framework 1.1 和 .NET Framework 2.0 应用程序提供 AJAX 支持。由 Iron Speed Designer V4.0 生成的应用程序会自动包含这些支持您的 AJAX 代码自定义所需的功能。

  • 在应用程序的 Bin 文件夹和项目文件中包含 Microsoft Atlas DLL(.NET 2.0)或 AjaxPro DLL(.NET 1.1)。
  • Web.config 中用于 Microsoft Atlas 支持(.NET Framework 2.0)或 AjaxPro 支持(.NET Framework 1.1)的更改。
  • 可以调用的 JavaScript 函数,用于显示弹出窗口(call-out)。

此外,从早期版本的 Iron Speed Designer 迁移过来的应用程序也会升级以支持 AJAX。简而言之,我们已经完成了基础工作,您可以实施利用 AJAX 强大功能的代码自定义。

Microsoft 目前仅通过 Atlas Framework 为 .NET Framework 2.0 应用程序提供原生支持。然而,对于 .NET Framework 1.1 应用程序,有许多支持 AJAX 的第三方框架可供使用。Iron Speed Designer 使用 AjaxPro.dll(一个免费的第三方 DLL)用于 .NET 应用程序。

使用 AJAX 编写 Call-Out 代码自定义

您可以轻松地将 AJAX 代码自定义添加到 Iron Speed Designer 生成的应用程序中。要添加各种 AJAX 代码自定义,只需添加几行 JavaScript 代码来处理 OnClickOnMouseOver 事件,以及从数据库检索和格式化数据。

以下示例演示了在使用 Iron Speed Designer V4.0 生成的应用程序中添加 AJAX 代码自定义的简便性。它使用 AJAX 异步调用页面代码隐藏文件中定义的方法,然后这些方法又会回调客户端 JavaScript 函数以在弹出窗口中显示数据。


Procedure

步骤 1:在 MouseOver 事件上调用 JavaScript 函数

首先定义一个用户可以鼠标悬停以查看弹出数据的区域。在此示例中,当用户将鼠标悬停在某条记录上时,将调用 MyCustomFunction() JavaScript 函数。此函数接受两个参数,第一个参数是鼠标悬停的记录的主键 ID。第二个参数是保留字 'event',它确定鼠标的位置。

在页面的 HTML 布局文件中,添加一个 <a OnMouseOver... /> HTML 标签来定义鼠标悬停区域。注意:请务必将其添加到 HTML 布局文件中,而不是添加到 Iron Speed Designer 生成的 ASPX 页面中。您可以使用 FieldValue 代码生成标签来指定 MyCustomFunction 第一个参数的主键 ID。确保在“页面属性”对话框中指定与 Field Value 代码生成标签对应的数据库字段。

<a OnMouseOver='MyCustomFunction(<GEN:FieldValue NAME="MyRecordID"/>, event);'>
    <GEN:FieldValue NAME="MyRecordName"/>
</a>

步骤 2:定义两个 JavaScript 函数来处理 OnMouseOver 事件

在 HTML 布局页面的 script 标签中定义两个 JavaScript 函数。第一个函数由 OnMouseOver 事件调用。此函数保存当前的鼠标位置,然后调用页面 Page 类代码隐藏文件中声明的 AJAX 方法。第二个函数是由(代码隐藏)AJAX 方法调用的回调函数。

正如下面所述,.NET Framework 1.1(使用 AjaxPro.dll)和 .NET Framework 2.0(使用 Microsoft Atlas)之间存在细微差别。

.NET Framework 1.1 应用程序
<script type ="text/javascript">
function MyCustomFunction(MyRecordID, event)
{
    // Save the mouse position for later use by detailRolloverPopup()
    SaveMousePosition(event);
 
    // Invoke the Ajax method defined in the code-behind of the page
    // Replace MYAPP with your application's name
    // and MYPAGE with the corresponding page class's name
    // Also, specify the callback function - MyCallBack (defined below)
    MYAPP.UI.MYPAGE.GetRecordDescription(MyRecordID, MyCallBack);
}
 
function MyCallBack(result)
{
    // The detailRollOverPopup() displays the content
    // returned from the Ajax call in a popup window
    // It accepts three parameters:
    // - aTitle, string to be displayed in the title bar of the popup window.
    // - aContent, string containing HTML to be displayed in the body of the popup.
    // - aPersist, boolean indicating whether the popup
    //   should remain visible even on mouseout.
    detailRolloverPopup('Window Title', result.value, false);
}
</script>
.NET Framework 2.0 应用程序

.NET Framework 2.0 应用程序的 AJAX 方法(在 Atlas 框架中称为“Web 方法”)可以定义在两个不同的位置:在页面的代码隐藏(*.vb*.cs)文件中,或在 Web 服务(*.asmx 文件)中。每种方法都有其优点。虽然 Web 服务保证了跨不同平台的互操作性,但它们可能存在安全问题。另一方面,在页面的代码隐藏中定义 Web 方法可以解决安全问题。

  1. 调用定义在页面代码隐藏文件中的 Web 方法。

    如果 Web 方法定义在页面的代码隐藏文件(MyPage.aspx.vbMyPage.aspx.cs)中,则使用 PageMethods JavaScript 命令来调用 Web 方法。PageMethods 命令调用当前页中的特定方法,从而无需 Web 服务。

    下面的 JavaScript 函数使用 PageMethods 命令调用定义在页面代码隐藏文件中的 Ajax Web 方法。请注意,此 JavaScript 函数应放置在 HTML 布局页面的脚本标签中。

    <script type ="text/javascript">
    function MyCustomFunction(MyRecordID, event)
    {
            // Save the mouse position for later use by detailRolloverPopup()
     
            SaveMousePosition(event);
            // Invoke the WebMethod defined in the code-behind
            // of the page through the PageMethods command
            // The PageMethods command will enable you to invoke
            // a specific method in the current page
            // eliminating the need for a web service.
            // Also, specify the callback function - MyCallBack (defined below)
            PageMethods.GetRecordDescription(MyRecordID, MyCallBack);
    }
     
    function MyCallBack(result)
    {
            // The detailRollOverPopup() displays the content
            // returned from the Ajax call in a popup window
            // It accepts three parameters:
            // - aTitle, string to be displayed in the title bar of the popup window.
            // - aContent, string containing HTML to be displayed in 
            //   the body of the popup.
            // - aPersist, boolean indicating whether the popup should
            //   remain visible even on mouseout.
            detailRolloverPopup('Window Title', result, false);
    }
    </script>
  2. 调用定义在 Web 服务中的 Web 方法。

    可以通过指定方法名和其所在 Web 服务来直接调用定义在 Web 服务中的 Web 方法。Web 服务(*.asmx 文件)可以通过 Visual Studio 的“添加新组件”选项添加,并保存在您的 Iron Speed Designer 生成的应用程序的根目录中。

    下面的 JavaScript 函数调用定义在 Web 服务中的 AJAX Web 方法。请注意,此 JavaScript 函数应放置在 HTML 布局页面的 script 标签中。

    <script type ="text/javascript">
    function MyCustomFunction(MyRecordID, event)
    {
            // Save the mouse position for later use by detailRolloverPopup()
     
            SaveMousePosition(event);
            // Invoke the web method defined in the Web Service.
            // This example assumes the name of the web service file created
            // to be MyWebService and the web method
            // defined in this web service to be GetRecordDescription.
            // Also, specify the callback function - MyCallBack (defined below)
            MyWebService.GetRecordDescription(MyRecordID, MyCallBack);
    }
     
    function MyCallBack(result)
    {
            // The detailRollOverPopup() displays the content returned
            // from the Ajax call in a popup window
            // It accepts three parameters:
            // - aTitle, string to be displayed in the title bar
            //   of the popup window.
            // - aContent, string containing HTML to be displayed
            //   in the body of the popup.
            // - aPersist, boolean indicating whether the popup
            //   should remain visible even on mouseout.
            detailRolloverPopup('Window Title', result, false);
    }
    </script>

步骤 3:向页面添加 ScriptManager 引用(仅限 .NET Framework 2.0)

注意:此步骤仅适用于为 .NET Framework 2.0 构建的应用程序。

在 HTML 布局页面中,包含 <atlas:ScriptManager> 元素。此标签使 Microsoft Atlas 客户端脚本在请求网页时能够下载,并启用该页面进行 Microsoft Atlas。请注意,此标签必须放置在页面的 <form> 标签内。ScriptManager 标签的定义取决于 Web 方法的定义位置。

  1. 定义在页面代码隐藏中的 Web 方法的 ScriptManager 标签
    <atlas:ScriptManager ID="scriptManager1" runat="server"/>
  2. 定义在 Web 服务中的 Web 方法的 ScriptManager 标签(在 ServiceReference 标签的 Path 属性中适当地指定 Web 服务文件的位置)
    <atlas:ScriptManager ID="scriptManager1" runat="server">
       <Services>
          <atlas:ServiceReference Path="../MyApp/MyWebService.asmx" />
       </Services>
    </atlas:ScriptManager>

步骤 4:在代码隐藏文件中添加代码

.NET Framework 1.1 应用程序
  1. 使用 RegisterTypeForAjax() 方法注册您的页面。

    对于 .NET Framework 1.1 应用程序,AjaxPro DLL 要求您注册被客户端 AJAX 调用调用的页面。RegisterTypeForAjax() 方法负责注册页面。在您添加了 HTML 和 JavaScript 标签的页面的代码隐藏文件中,在 PageLoad 方法中调用 RegisterTypeForAjax()。此方法接受 Page 类的名称作为参数。在这种情况下,需要将调用 Page Load 事件的 Page 类的名称指定为参数。

  2. 使用 AjaxPro.AjaxMethod 定义 AJAX 方法。

    所有 AJAX 方法都必须使用 AjaxPro.AjaxMethod 命令声明。这使得您的服务器端方法可以从客户端 JavaScript 调用。在我们的示例中,服务器端 GetRecordDescription() 方法接受记录的 ID 作为参数,构造一个 'WHERE' 子句,该子句用于根据记录 ID 检索选定记录的详细信息,并将指定记录的描述返回给客户端回调函数。

C#, .NET Framework 1.1
public class MYPAGE: BaseApplicationPage
{
  private void MYPAGE_Load(object sender, System.EventArgs e)
  {
        // Register the page class so that client-side JavaScript can call an
        // AjaxMethod.
        // Change MYPAGE to the corresponding name of the page class.
        AjaxPro.Utility.RegisterTypeForAjax(GetType(MYPAGE));
  }
  // Define all Ajax methods in .NET 1.1 with the AjaxMethod tag.
  // Replace <Record ID> with the Id field of your database table.
  // Replace <Table Name> with the name of your database table.
  // Replace <Description Field> with the name of a description field from your
  // database table.
  [AjaxPro.AjaxMethod]
  public string GetRecordDescription(int MyRecordID)
  {
        // For INTEGER Id's
        string whereStr = " <Record ID> = " + MyRecordID;
        // For STRING Id's, comment the line above and uncomment the line below.
        // string whereStr = " <Record ID> = '" + MyRecordID + "'";
        <Table Name>Record selectedRecord = <Table Name>Table.GetRecord(whereStr);
        // In this example the description of the selected record is retrieved
        string content = "The description for the selected record is " + 
                         selectedRecord.<Description Field>;
        return content;
  }
}
Visual Basic .NET, .NET Framework 1.1
Public Class MYPAGE Inherits BaseApplicationPage
Private Sub MYPAGE_Load(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
     ' Register the page class so that client-side JavaScript can
     ' call an AjaxMethod.
     ' Change MYPAGE to the name of the page class.
     AjaxPro.Utility.RegisterTypeForAjax(GetType(MYPAGE))
End Sub
 
' Define all web methods in .NET 1.1 with the AjaxMethod tag.
' Replace <Record ID> with the Id field of your database table.
' Replace <Table Name> with the name of your database table.
' Replace <Description Field> with the name of a description field from your
' database table.
<AjaxPro.AjaxMethod()> _
Public Function GetRecordDescription(ByVal MyRecordID As Integer) As String
     ' For INTEGER Id's
     Dim whereStr As String = "<Record ID> = " & MyRecordID
     ' For STRING Id's, comment the line above and uncomment the line below.
     Dim whereStr As String = "<Record ID> = '" & MyRecordID & "'"
     Dim rec As <Table Name>Record = <Table Name>Table.GetRecord(whereStr)
     ' In this example the description of the selected record is
     ' retrieved.
     Dim content As String = "The description for the chosen record is" & _
                             rec.<Description Field>
     Return content
End Function
End Class
.NET Framework 2.0 应用程序

在页面的代码隐藏文件(MyPage.aspx.vbMyPage.aspx.cs)或 Web 服务文件(MyWebService.asmx)中定义将记录的描述返回给客户端函数的服务器端 Web 方法。所有 Web 方法都必须使用 System.WebServices.WebMethod 命令声明,该命令使服务器端 Web 方法可以从客户端 JavaScript 调用,并使这些 Web 方法返回的结果可供客户端回调函数使用。

C#, .NET Framework 2.0
  1. 定义在页面代码隐藏文件中的 Web 方法
    partial class MyPage : BaseApplicationPage
    // Code-behind class for the MyPage page.
    // Place your customizations in Section 1. Do not modify Section 2.
    {
      #region "Section 1: Place your customizations here."
         // Define all web methods in .NET 2.0 within the WebMethod tag.
         // Replace <Record ID> with the Id field of your database table.
         // Replace <Table Name> with the name of your database table.
         // Replace <Description Field> with the name of a description field from your
         // database table.
         [System.Web.Services.WebMethod()]
         public string GetRecordDescription(int MyRecordID)      {
            // For INTEGER Id's
            string whereStr = " <Record ID> = " + MyRecordID;
            // For STRING Id's, comment the line above and uncomment the line below.
            // string whereStr = " <Record ID> = '" + MyRecordID + "'";
            <Table Name>Record selectedRecord = <Table Name>Table.GetRecord(whereStr);
            // In this example the description of the selected record is retrieved
            string content = "The description for the selected record is " + 
                selectedRecord.<Description Field>;
            return content;
         }
      #endregion 
      #region "Section 2: Do not modify this section."
         :
         :
      #endregion
    }
  2. 定义在 MyWebService.asmx 文件中的 Web 方法
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
     
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    
    public class WebService : System.Web.Services.WebService
    {
         // Define all web methods in .NET 2.0 within the WebMethod tag.
         // Replace <Record ID> with the Id field of your database table.
         // Replace <Table Name> with the name of your database table.
         // Replace <Description Field> with the name
         // of a description field from your database table.
         [WebMethod]
         public string GetRecordDescription(int MyRecordID)
         {
            // For INTEGER Id's
            string whereStr = " <Record ID> = " + MyRecordID;
            // For STRING Id's, comment the line above and uncomment the line below.
            // string whereStr = " <Record ID> = '" + MyRecordID + "'";
            <Table Name>Record selectedRecord = <Table Name>Table.GetRecord(whereStr);
            // In this example the description of the selected record is retrieved
            string content = "The description for the selected record is " + 
                             selectedRecord.<Description Field>;
            return content;
         }
    }
Visual Basic .NET, .NET Framework 2.0
  1. 定义在页面代码隐藏文件中的 Web 方法
    Partial Class MyPage Inherits BaseApplicationPage
    ' Code-behind class for the MyPage page.
    ' Place your customizations in Section 1. Do not modify Section 2.
     
      #Region "Section 1: Place your customizations here."
      ' Define all web methods within the WebMethod tag.
      ' Replace <Record ID> with the Id field of your database table.
      ' Replace <Table Name> with the name of your database table.
      ' Replace <Description Field> with the name of a description field from your
      ' database table.
      <Services.WebMethod()> _
            Public Function GetRecordDescription(ByVal MyRecordID As Integer) As String
               ' For INTEGER Id's
               Dim whereStr As String = "<Record ID> = " & MyRecordID
               ' For STRING Id's, comment the line above and uncomment the line below.
               ' Dim whereStr As String = "<Record ID> = '" & MyRecordID & "'"
               Dim rec As <Table Name>Record = <Table Name>Table.GetRecord(whereStr)
               'In this example the description of the selected record is retrieved
               Dim content As String = "The description for the chosen record is " & _
                                       rec.<Description Field>
               Return content
            End Function
      #End Region
      #Region "Section 2: Do not modify this section."
         :
         :
      #End Region
    End Class
  2. 定义在 WebService.asmx 文件中的 Web 方法
    <%@ WebService Language="VB" Class="MyWebService" %>
    Imports System.Web
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
     
    Public Class MyWebService Inherits System.Web.Services.WebService
         ' Define all web methods within the WebMethod tag.
         ' Replace <Record ID> with the Id field of your database table.
         ' Replace <Table Name> with the name of your database table.
         ' Replace <Description Field> with the name of a description field from your
         ' database table.
         <WebMethod()> _
            Public Function GetRecordDescription(ByVal MyRecordID As Integer) As String
               ' For INTEGER Id's
               Dim whereStr As String = "<Record ID> = " & MyRecordID
               ‘ For STRING Id's, comment the line above and uncomment the line below.
               ' Dim whereStr As String = "<Record ID> = '" & MyRecordID & "'"
               Dim rec As <Table Name>Record = <Table Name>Table.GetRecord(whereStr)
               'In this example the description of the selected record is retrieved
               Dim content As String = 
                   "The description for the chosen record is " & rec.
               Return content
            End Function
    End Class

步骤 5:构建并运行应用程序

就这样!当您将鼠标悬停在应用程序中选择的字段上时,您应该会看到一个格式精美的呼出气泡。

参考文献

最新的 AJAX .NET DLL 可在此处下载:这里

您可以参考以下网站获取更多详细信息和简单的 AJAX 示例

© . All rights reserved.