Asp.net Ajax框架教程

目录
().概述...
().应用场景代码示例...
1).ScriptManager控件示例...
     1. 在异步调用服务端注册客户端脚本新方法...
     2. 捕获Ajax异步调用中错误(默认使用alert提示).
     3. 捕获Ajax异步调用中错误(自定义输出错误方式)
2).UpdatePanel控件示例...
     4. RenderMode属性用法示例...
     5. UpdateMode用法示例...
     6. ChildrenAsTriggers属性用法示例...
     7. Triggers属性用法示例...
3). UpdateProgress控件示例...
     8. 在异步更新时显示滚动进度条...
4). Timer控件示例...
     9.在客户端无刷新定时执行服务端方法...
5). Ajax中新Validators控件用法示例...
     10. Validators控件使用配置示例...
6). 在客户端请求服务端最基本的执行方式...
     11. 使用Ajax library类库中的客户端WebReqest对象请求服务端...
7). 在客户端调用页面后台(Page behind)中方法...
     12. 在客户端调用页面后台(Page behind)中方法示例...
8). 在客户端调用WebService中的服务端方法...
     13. 调用WebService示例...
9). 错误回调处理...
     14. 掌握客户端错误回调处理方法...
10). Ajax library客户端编程特性...
     15. Asp.net Ajax框架中的客户端对象与服务端对象交互...
     16.DataSet/DataTable/DataRow正反序列化JSON格式程序集使用...
     17. 客户端类使用Sys.StringBuilder使用示例...
     18. WebRequestManager对象的客户端事件示例...
11). Ajax操作中访问 Session-Cache-Application 对象...
     19. WebService方法中使用Session/Cache/Application对象...
     20. Page后台方法中使用Session/Cache/Application对象...
12). Ajax 客户端类库对现有 javascript对象的扩展功能...
     21. 扩展Array对象方法forEach使用示例...
     22. JavaScript Function对象扩展, 注册事件新方式...
     23. AjaxString对象扩展方法String.format的使用...
13). Ajax library中的客户端面向对象(OO)功能...
     24. 客户端注册命名空间, 定义接口, 类继承示例...
14). Asp.net Ajax 中的多语功能...
     25. Asp.net服务端使用全局和本地资源文件示例...
     26. Asp.net客户端使用全局和本地资源文件示例...
 
 
( ).概述
业余时间学习了一下微软的 Asp.net Ajax框架教程, 在学习时顺便整理了一个教程. 此教程包括26个精简的小例子, 主要针对开发应用场景和功能点进行展开示例, 在实际开发中也可以作为查找手册使用. 注释都在每个示例中.
Asp.net Ajax客户端对 Ajax编程支持非常丰富, 因此使用起来比较灵活.      --ChengKing(ZhengJian)
( ).应用场景代码示例
1).ScriptManager 控件示例
1. 在异步调用服务端注册客户端脚本新方法
前台页面代码:
< body >
    <form id="form1" runat="server">
    <div>
       
               
                     
        <asp:ScriptManager ID="ScriptManager1" runat="server">
         asp:ScriptManager>
         <asp:UpdatePanel ID="UpdatePanel1" runat="server">
              <ContentTemplate>
                   当前时间: <%= DateTime.Now %>
                   <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click1" />
              ContentTemplate>
         asp:UpdatePanel>         
    div>
    form>
body >
 
后台服务端代码:
public partial class _AA_ScriptManager_RegistClientScript_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        //Ajax 框架中新调用方式
        ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "UpdateSucceed", "alert('Update time succeed!')", true);       
 
        // 默认调用方式(在异步调用XmlHttp方式中无效)
        //Page.ClientScript.RegisterStartupScript(this.GetType(), "UpdateSucceed", "");
    }
}
2. 捕获Ajax异步调用中错误(默认使用alert提示)
前台页面代码:
< body >
    <form id="form1" runat="server">
    <div>
     
       
                       
       
        <asp:ScriptManager ID="ScriptManager1" runat="server" AllowCustomErrorsRedirect="false" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError">
         asp:ScriptManager>
         <asp:UpdatePanel ID="UpdatePanel1" runat="server">
              <ContentTemplate>
                   <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
              ContentTemplate>
         asp:UpdatePanel>    
        
    div>
    form>
body >
 
后台页面代码:
public partial class _AA_ScriptManager_GetAsycError_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void Button1_Click(object sender, EventArgs e)
    {       
        int a = 5, b = 0;
        int c = a / b;
    }
    protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
    {
        ScriptManager.GetCurrent(this).AsyncPostBackErrorMessage = e.Exception.Message;
    }
}
3. 捕获Ajax异步调用中错误(自定义输出错误方式)
前台页面代码:
< body >
    <form id="form1" runat="server">
    <div>
       
                       
       
                
     
        <asp:ScriptManager ID="ScriptManager1" runat="server" AllowCustomErrorsRedirect="false">
         asp:ScriptManager>
         <asp:UpdatePanel ID="UpdatePanel1" runat="server">
              <ContentTemplate>
                   <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
              ContentTemplate>
         asp:UpdatePanel>
        
         <div id="divMessage" style="color:Red;">div>
         <script type="text/javascript" language="javascript">
              Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, e)
              {
                   e.set_errorHandled(true); // 表示自定义显示错误, 将默认的alert提示禁止掉.
                   $get("divMessage").innerHTML = e.get_error().message;                
              });
         script>
    div>
form >
body >
 
后台服务端代码:
public partial class _AA_ScriptManager_GetAsycDetailError_CustomDisplayError_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        int a = 5, b = 0;
        int c = a / b;
    }
}
2).UpdatePanel 控件示例
4. RenderMode 属性用法示例
< body >
    <form id="form1" runat="server">
    <div>
       
       
   
        <asp:ScriptManager ID="ScriptManager1" runat="server">
         asp:ScriptManager>
   
         <asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Block">
              <ContentTemplate>
                   UpdatePanel1(Display 设置为Block)
              ContentTemplate>
         asp:UpdatePanel>
         <asp:UpdatePanel ID="UpdatePanel2" runat="server" RenderMode="Block">
              <ContentTemplate>
                   UpdatePanel2(Display 设置为Block)
              ContentTemplate>
         asp:UpdatePanel>
        
        
         <asp:UpdatePanel ID="UpdatePanel3" runat="server" RenderMode="Inline">
              <ContentTemplate>
                   UpdatePanel3(Display 设置为Inline)
              ContentTemplate>
         asp:UpdatePanel>    
         <asp:UpdatePanel ID="UpdatePanel4" runat="server" RenderMode=Inline>
              <ContentTemplate>
                   UpdatePanel4(Display 设置为Inline)
              ContentTemplate>
         asp:UpdatePanel>    
    div>
form >
body >
5. UpdateMode 用法示例
< body >
    <form id="form1" runat="server">
    <div>
       
               
       
       
       
        <asp:ScriptManager ID="ScriptManager1" runat="server">
         asp:ScriptManager>
         <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode=always>
              <ContentTemplate>
                   UpdatePanel1 时间:<%= DateTime.Now %>
                   <asp:Button ID="Button1" runat="server" Text="Button" />
              ContentTemplate>
         asp:UpdatePanel>    
        
         <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode=conditional>
              <ContentTemplate>
                   UpdatePanel2 时间:<%= DateTime.Now %>
                   <asp:Button ID="Button2" runat="server" Text="Button" />
              ContentTemplate>
         asp:UpdatePanel>
         <br />
        
    div>
form >
body >
6. ChildrenAsTriggers 属性用法示例
< body >
    <form id="form1" runat="server">
    <div>
       
               
               
       
        <asp:ScriptManager ID="ScriptManager1" runat="server">
         asp:ScriptManager>
         <asp:UpdatePanel ID="UpdatePanel1" runat="server">
              <ContentTemplate>
                   UpdatePanel1 时间: <%= DateTime.Now %>
              ContentTemplate>
         asp:UpdatePanel>
         <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode=conditional ChildrenAsTriggers="false">
              <ContentTemplate>
                   UpdatePanel2 时间: <%= DateTime.Now %>
                   <asp:Button ID="Button1" runat="server" Text="Button" />
              ContentTemplate>
         asp:UpdatePanel>
 
    div>
    form>
body >
7. Triggers 属性用法示例
< body >
    <form id="form1" runat="server">
    <div>
       
               
             
        <asp:ScriptManager ID="ScriptManager1" runat="server">
         asp:ScriptManager>
         <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
              <ContentTemplate>
                   当前时间: <%= DateTime.Now %>
                   <asp:Button ID="Button1" runat="server" Text="Button" />
              ContentTemplate>
              <Triggers>            
                   <asp:PostBackTrigger ControlID="Button2" />                 
                   <asp:AsyncPostBackTrigger ControlID="Button3" />
              Triggers>           
         asp:UpdatePanel>
        
         <asp:UpdatePanel ID="UpdatePanel2" runat="server">
              <ContentTemplate>               
                   <asp:Button ID="Button2" runat="server" Text="Button" />
              ContentTemplate>
         asp:UpdatePanel>   
         <asp:UpdatePanel ID="UpdatePanel3" runat="server">
              <ContentTemplate>               
                   <asp:Button ID="Button3" runat="server" Text="Button" />
              ContentTemplate>
         asp:UpdatePanel>   
    div>
    form>
body >
3). UpdateProgress 控件示例
8. 在异步更新时显示滚动进度条
< body >
    <form id="form1" runat="server">
    <div>
       
               
             
             
             
      
        <asp:ScriptManager ID="ScriptManager1" runat="server">
         asp:ScriptManager>
 
         <asp:UpdateProgress ID="UpdateProgress1" runat="server" DynamicLayout=false AssociatedUpdatePanelID="UpdatePanel1" DisplayAfter="1000">
              <ProgressTemplate>
                <asp:Image ID="Image1" runat="server" ImageUr="~/(C)UpdateProgress/(8)UpdateProgress/Progress.gif" ImageUrl="~/(C)UpdateProgress/(8)UpdateProgress/Progress.gif" />
              ProgressTemplate>
         asp:UpdateProgress>
 
 
         <asp:UpdatePanel ID="UpdatePanel1" runat="server">
              <ContentTemplate>
                   当前时间: <%= DateTime.Now %>
                   <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
              ContentTemplate>
         asp:UpdatePanel>   
    div>
    form>
body >
4). Timer 控件示例
9. 在客户端无刷新定时执行服务端方法
< body >
    <form id="form1" runat="server">
    <div>
   
       
               
             
                     
       
        <asp:ScriptManager ID="ScriptManager1" runat="server">
         asp:ScriptManager>
         <asp:UpdatePanel ID="UpdatePanel1" runat="server">
              <ContentTemplate>
                   当前时间: <%= DateTime.Now %>
                   <asp:Timer ID="Timer1" runat="server" Interval="1000">
                   asp:Timer>
              ContentTemplate>
         asp:UpdatePanel>
         <%--
    -- %>
    <%--
             
                   当前时间: <%= DateTime.Now %>                 
             
         -- %>
    div>
    form>
body >
5). Ajax 中新Validators控件用法示例
使用VS 2005默认的验证控件在异步操作时会有些问题, 微软推出与现有控件名称一一对应的一系列验证控件
10. Validators 控件使用配置示例
< body >
    <form id="form1" runat="server">
    <div>
       
       
               
             
            
       
        <asp:ScriptManager ID="ScriptManager1" runat="server">
         asp:ScriptManager>
         <asp:UpdatePanel ID="UpdatePanel1" runat="server">
              <ContentTemplate>
                   <asp:TextBox ID="TextBox1" runat="server">asp:TextBox>
                   <asp:RequiredFieldValidator ControlToValidate="TextBox1" ID="RequiredFieldValidator1" runat="server" ErrorMessage=" 不能为NULL!"> asp : RequiredFieldValidator >                
                   <br />
                   <asp:Button ID="Button1" runat="server" Text="Button" />
              ContentTemplate>
         asp:UpdatePanel>   
    div>
    form>
body >
6). 在客户端请求服务端最基本的执行方式
11. 使用Ajax library类库中的客户端WebReqest对象请求服务端
前台页面代码:
< body >
    <form id="form1" runat="server">
   
       
             
       
        <asp:ScriptManager ID="ScriptManager1" runat="server">
         asp:ScriptManager>
        
         <script language="jscript" type="text/javascript">
              function ExecuteAjaxRequest(text)
              {
                   var request = new Sys.Net.WebRequest();
                   request.set_url('ClientWebRequest.ashx');
                   request.set_httpVerb("POST");
                   request.add_completed(onComplete);
                                
                      
                   request.set_body('text=' + encodeURIComponent(text));                
                   request.invoke();
              }
             
              function onComplete(response)
              {
                   if (response.get_responseAvailable())
                   {
                       var text = response.get_object();
                       alert(text);
                   }
              }
         script>
        
         <input type="button" value="Hello Word!" onclick="ExecuteAjaxRequest('Hello Word!')" />      
form >
body >
 
处理程序ashx文件代码:
using System;
using System.Web;
 
using System.Web.Script.Serialization;
 
public class ClientWebRequest : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
       
        context.Response.ContentType = "text/plain";      
        string text = context.Request.Params["text"];       
 
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
 
        context.Response.Write(jsSerializer.Serialize(text));
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
 
}
7). 在客户端调用页面后台(Page behind)中方法
12. 在客户端调用页面后台(Page behind)中方法示例
前台页面代码:
< body >
    <form id="form1" runat="server">
    <div>
       
       
                       
       
       
       
             
         <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
        
         <input type="button" value=" 调用服务端方法" onclick="ExecuteServerMethod('ChengKing')" />
   
         <script language="javascript" type="text/javascript">
              function ExecuteServerMethod(value)
              {
                   PageMethods.ReturnStringServerMethod(value,CallBackResult);
              }
             
              function CallBackResult(result)
              {
                   alert(result);
              }
         script>
        
    div>
    form>
body >
页面后台服务端代码:
using System.Web.Services;
public partial class _G_Ajax_Visit_PageServer_Method_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    [WebMethod]
    public static string ReturnStringServerMethod(string str)
    {       
        return "Hello " + str;
}
}
8). 在客户端调用WebService中的服务端方法
13. 调用WebService示例
前台页面代码:
< body >
    <form id="form1" runat="server">
    <div>
   
       
               
       
        
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="SimpleTransferWebservice.asmx" InlineScript=false />
            Services>
        asp:ScriptManager>
        <script language="javascript" type="text/javascript">
              function showEmployee(str)
              {
                   SimpleTransferWebservice.HelloWorld(              
                       str,
                       onCompleted);
              }            
              function onCompleted(response)
              {
                   alert(response);
              }
         script>
        
         <input type="button" value="Hello Word!"
              onclick="showEmployee(this.value)" />
    div>
form >
body >
 
Webservice 后台代码(*.asmx页面):
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class SimpleTransferWebservice : System.Web.Services.WebService {
 
    public SimpleTransferWebservice () {
 
        // 如果使用设计的组件,请取消注释以下行
        //InitializeComponent();
    }
 
    [WebMethod]
    [ScriptMethod]
    public string HelloWorld
        (string str) {
        return str;
    }   
}
9). 错误回调处理
14. 掌握客户端错误回调处理方法
前台页面代码:
< body >
    <form id="form1" runat="server">
    <div>
   
       
       
       
             
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods=true>            
         asp:ScriptManager>
        
         <input type="button" value=" 一般错误异常" onclick="Division(1, 0)" />
         <input type="button" value=" 超时异常" onclick="Timeout()" />
        
         <script language="javascript" type="text/javascript">
              function Division(a, b)
              {
                   PageMethods.Division(a, b, null, ErrorCallback);
              }
             
              function Timeout()
              {
                   PageMethods.set_timeout(1000);
                   PageMethods.Timeout(null, ErrorCallback);
              }
             
              function ErrorCallback(e)
              {
                   var OupPutMessage = String.format(" 是否超时: {0}/n错误信息: {1}/n异常类型: {2}/n堆栈跟踪: {3}" ,e.get_timedOut(),e.get_message(),e.get_exceptionType(),e.get_stackTrace());        
                   alert(OupPutMessage);
              }
         script>   
    div>
form >
body >
 
后台服务端代码:
using System.Threading;
using System.Web.Services;
 
public partial class _I_FailedCallback_Process_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    [WebMethod]
    public static int Division(int a,int b)
    {
        return a/b;
    }
    [WebMethod]
    public static void Timeout()
    {
        Thread.Sleep(2000); // 超时情况       
    }
}
10). Ajax library 客户端编程特性
15. Asp.net Ajax 框架中的客户端对象与服务端对象交互
前台页面代码:
< body >
    <form id="form1" runat="server">
    <div>
   
       
       
               
             
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods=true>            
         asp:ScriptManager>       
         <input type="button" value=" 客户端对象传递到服务端" onclick="Add1000Salary()" />       
         <input type="button" value=" 服务端对象传递到客户端" onclick="GetServerObject()" />     
         <script language="javascript" type="text/javascript">
              function Add1000Salary()
              {   
                  // 如果Person不在App_Code中, 则使用方式如:var person = new 命名空间.Person();          
                   var person = new Person(); //or var person = new Object();
                  
                   person.Name = "Rose Zhao";
                   person.Sex = "Female";
                   person.Salary = 2000;               
                   PageMethods.Add_1000_Salary(person, Add_1000_SalarySucceeded);
              }            
              function Add_1000_SalarySucceeded(result)
              {
                   var message = String.format(" 姓名: {0}; 性别: {1}; 工资: {2}" ,result.Name, result.Sex, result.Salary);                   
                   alert(message);
              }                 
             
              function GetServerObject()
              {
                   PageMethods.GetOnePerson(GetServerObjectSucceeded);
              }            
              function GetServerObjectSucceeded(result)
              {
                   for (var key in result)
                   {                     
                       var message = String.format(
                       " 姓名: {0}; 性别: {1}; 工资: {2}" ,result[key].Name, result[key].Sex, result[key].Salary);                     
                       alert(message);
                   }
              }
             
        script>
    div>
form >
body >
 
后台服务端代码:
using System.Web.Services;
using System.Collections.Generic;
public partial class _J_Use_ClientObject_in_Ajax_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {      
    }
    [WebMethod]
    public static Person Add_1000_Salary(Person person)
    {
        person.Salary += 1000;
        return person;
    }
    [WebMethod]
    public static IDictionary<string, Person> GetOnePerson()
    {
        Dictionary<string, Person> result = new Dictionary<string, Person>();
        Person person = new Person();
        person.Name = "Rose Zhao";
        person.Sex = "Female";
        person.Salary = 2000;
        result[person.Name] = person;
        return result;
    }
}
 
16.DataSet/DataTable/DataRow 正反序列化JSON格式程序集使用
前台页面代码:
< body >
    <form id="form1" runat="server">
    <div>
   
       
       
            
       
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods=true>            
         asp:ScriptManager>       
         <input type="button" value=" 获取数据" onclick="GetPersonDataTable();" />                         
         <script language="javascript" type="text/javascript">
              function GetPersonDataTable()
              {
                   PageMethods.GetPersonDataTable(CallBackProcessResultMethod,ErrorHandler);
              }
             
              function CallBackProcessResultMethod(result)
              {           
                   var sb = new Sys.StringBuilder("");
                   sb.append("
");
                   for (var i = 0; i < result.rows.length; i++)
                   {
                        sb.append(String.format("
",result.rows[i]["Name"],result.rows[i].Sex, result.rows[i].Salary));
                   }
                   sb.append("
姓名性别工资
{0}{1}{2}
"
);              
                   $get("table").innerHTML = sb.toString();
              }   
             
              function ErrorHandler(error)
              {
                   alert(error.get_message());
              }            
         script>    
         <br />
         <div id="table">div>
    div>
form >
body >
 
后台页面代码:
using System.Web.Services;
using System.Web.Script.Serialization;
public partial class _J_Ajax_Client_Programe__B_JS_StringBuilder_Class_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    [WebMethod]       
    public static DataTable GetPersonDataTable()
    {
        //return "abc";
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Sex", typeof(string)));
        dt.Columns.Add(new DataColumn("Salary", typeof(string)));
 
        DataRow drNew = dt.NewRow();
        drNew["Name"] = "Rose Zhao";
        drNew["Sex"] = "Female";
        drNew["Salary"] = "2000";
        dt.Rows.Add(drNew);
 
        drNew = dt.NewRow();
        drNew["Name"] = "King Zheng";
        drNew["Sex"] = "male";
        drNew["Salary"] = "3000";
        dt.Rows.Add(drNew);      
 
        return dt;
    }
}
17. 客户端类使用Sys.StringBuilder使用示例
前台页面代码
< body >
    <form id="form1" runat="server">
    <div>
   
       
               
       
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods=true>            
         asp:ScriptManager>       
         <input type="button" value=" 获取数据" onclick="GetPersonDataTable();" />                         
         <script language="javascript" type="text/javascript">
              function GetPersonDataTable()
              {
                   PageMethods.GetPersonDataTable(CallBackProcessResultMethod,ErrorHandler);
              }
             
              function CallBackProcessResultMethod(result)
              {           
                   var sb = new Sys.StringBuilder("");
                   sb.append("
");
                   for (var i = 0; i < result.rows.length; i++)
                   {
                        sb.append(String.format("
",result.rows[i]["Name"],result.rows[i].Sex, result.rows[i].Salary));
                   }
                   sb.append("
姓名性别工资
{0}{1}{2}
"
);              
                   $get("table").innerHTML = sb.toString();
              }   
             
              function ErrorHandler(error)
              {
                   alert(error.get_message());
              }            
         script>    
         <br />
         <div id="table">div>
    div>
    form>
body >
后台页面代码:
using System.Web.Services;
using System.Web.Script.Serialization;
 
public partial class _J_Ajax_Client_Programe__B_JS_StringBuilder_Class_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    [WebMethod]   
    public static DataTable GetPersonDataTable()
    {
        //return "abc";
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Sex", typeof(string)));
        dt.Columns.Add(new DataColumn("Salary", typeof(string)));
 
        DataRow drNew = dt.NewRow();
        drNew["Name"] = "Rose Zhao";
        drNew["Sex"] = "Female";
        drNew["Salary"] = "2000";
        dt.Rows.Add(drNew);
 
        drNew = dt.NewRow();
        drNew["Name"] = "King Zheng";
        drNew["Sex"] = "male";
        drNew["Salary"] = "3000";
        dt.Rows.Add(drNew);      
 
        return dt;
    }
}
18. WebRequestManager 对象的客户端事件示例
< body >
    <form id="form1" runat="server">
    <div>
   
   
     
   
   
    <script language="javascript">
              Sys.Net.WebRequestManager.add_invokingRequest(function(sender, eventArgs)
              {
                   if (confirm(" 是否取消本操作?" ))
                   {
                       eventArgs.set_cancel(true);                   
                   }
              });          
              Sys.Net.WebRequestManager.add_completedRequest(function()
              {
                   alert(" 刷新时间操作成功!" );
              });
         script>
        
        <asp:ScriptManager ID="ScriptManager1" runat="server" />     
         <asp:UpdatePanel ID="UpdatePanel1" runat="server">
              <ContentTemplate>
                   <asp:Button ID="Button1" runat="server" Text=" 更新当前时间[无刷新]" />
                   <br /><br />
                   当前时间: <%= DateTime.Now.ToString() %>               
              ContentTemplate>
         asp:UpdatePanel>
        
         <asp:Button ID="Button2" runat="server" Text=" 更新当前时间[刷新]" />
    div>
    form>
body >
11). Ajax操作中访问 Session-Cache-Application 对象
19. WebService方法中使用Session/Cache/Application对象
前台页面代码:
< body >
    <form id="form1" runat="server">
    <div>
   
       
               
               
        <asp:ScriptManager runat="server" ID="ScriptManager1">            
            <Services>
                   <asp:ServiceReference Path="UseSession_etc.asmx" InlineScript="true" />
              Services>
         asp:ScriptManager>   
        
         <input type="button" value=" 改变服务端Session中存储的值" onclick="ChangeSession()" />
         <input type="button" value=" 改变服务端Cache中存储的值" onclick="ChangeCache()" />
         <input type="button" value=" 改变服务端Application中存储的值" onclick="ChangeApplication()" />
    
         <script language="javascript" type="text/javascript">
              function ChangeSession()
              {
                   UseSession_etc.ChangeSession(ChangeSucceeded);
              }
              function ChangeCache()
              {
                   UseSession_etc.ChangeCache(ChangeSucceeded);
              }
              function ChangeApplication()
              {
                   UseSession_etc.ChangeApplication(ChangeSucceeded);
              }
             
              function ChangeSucceeded(result)
              {
                   alert(result);
              }
         script>    
    div>
form >
body >
 
WebService 页面后台代码(*.asmx) :
///
/// UseSession_etc 的摘要说明
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UseSession_etc : System.Web.Services.WebService {
 
    public UseSession_etc () {
 
        // 如果使用设计的组件,请取消注释以下行
        //InitializeComponent();     
    }
 
    [WebMethod(EnableSession=true)]
    public int ChangeSession()
    {
        if (Session["count"] == null)
        {
            Session["count"] = "0";
        }
 
        int intCount = int.Parse(Session["count"].ToString());
        intCount++;
        Session["count"] = intCount;
        return intCount;
    }
 
    [WebMethod]
    public int ChangeCache()
    {
        if (this.Context.Cache["count"] == null)
        {
            this.Context.Cache["count"] = "0";
        }
        int intCount = int.Parse(this.Context.Cache["count"].ToString());
        intCount++;
        this.Context.Cache["count"] = intCount;
        return intCount;
    }
 
    [WebMethod]
    public int ChangeApplication()
    {
        if (Application["count"] == null)
        {
            Application["count"] = "0";
        }
        int intCount = int.Parse(Application["count"].ToString());
        intCount++;
        Application["count"] = intCount;
        return intCount;
    }   
}
20. Page后台方法中使用Session/Cache/Application对象
前台页面代码:
< body >
    <form id="form1" runat="server">
    <div>
   
       
          
       
        <asp:ScriptManager runat="server" ID="ScriptManager1" EnablePageMethods=true>                        
         asp:ScriptManager>   
        
         <input type="button" value=" 改变服务端Session中存储的值" onclick="ChangeSession()" />
         <input type="button" value=" 改变服务端Cache中存储的值" onclick="ChangeCache()" />
         <input type="button" value=" 改变服务端Application中存储的值" onclick="ChangeApplication()" />
    
         <script language="javascript" type="text/javascript">
              function ChangeSession()
              {
                   PageMethods.ChangeSession(ChangeSucceeded);
              }
              function ChangeCache()
              {
                   PageMethods.ChangeCache(ChangeSucceeded);
              }
              function ChangeApplication()
              {
                   PageMethods.ChangeApplication(ChangeSucceeded);
              }
             
              function ChangeSucceeded(result)
              {
                   alert(result);
              }
         script>    
    div>
form >
body >
 
页面后台代码
using System.Web.Services;
using System.Web.SessionState;
using System.Web.Caching;
public partial class _K_EnableSession_in_Ajax_Progam_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Session["count"] = "0";
        //Cache["count"] = "0";
        //Application["count"] = "0";              
    }
 
    [WebMethod(EnableSession = true)]
    public static int ChangeSession()
    {
        if (System.Web.HttpContext.Current.Session["count"] == null)
        {
            System.Web.HttpContext.Current.Session["count"] = "0";
        }
 
        int intCount = int.Parse(System.Web.HttpContext.Current.Session["count"].ToString());
        intCount++;
        System.Web.HttpContext.Current.Session["count"] = intCount;
        return intCount;
    }
 
    [WebMethod]
    public static int ChangeCache()
    {
        if (System.Web.HttpContext.Current.Cache["count"] == null)
        {
            System.Web.HttpContext.Current.Cache["count"] = "0";
        }
        int intCount = int.Parse(System.Web.HttpContext.Current.Cache["count"].ToString());
        intCount++;
        System.Web.HttpContext.Current.Cache["count"] = intCount;
        return intCount;
    }
 
    [WebMethod]
    public static int ChangeApplication()
    {
        if (System.Web.HttpContext.Current.Application["count"] == null)
        {
            System.Web.HttpContext.Current.Application["count"] = "0";
        }
        int intCount = int.Parse(System.Web.HttpContext.Current.Application["count"].ToString());
        intCount++;
        System.Web.HttpContext.Current.Application["count"] = intCount;
        return intCount;
    }
}
 
12). Ajax 客户端类库对现有 javascript对象的扩展功能
21. 扩展Array对象方法forEach使用示例
< body >
    <form id="form1" runat="server">
    <div>
        
       
             
       
        <asp:ScriptManager ID="ScriptManager1" runat="server" />   
         <script language="javascript" type="text/javascript">
                           
              var str = "Hello Rose Zhao".split(" ");
              var obj = {returnValue : ""};
              Array.forEach(str, tidy, obj);// 参数1: 要整理的字符串; 参数2: 委托的客户端方法名称; 参数3: 存放结果的对象.             
              alert(obj.returnValue);
             
              function tidy(elt, index, array)
              {
                   this.returnValue += "[" + elt + "] ";
              }
             
         script>
    div>
    form>
body >
22. JavaScript Function对象扩展, 注册事件新方式
< body >
    <form id="form1" runat="server">
    <div>
       
       
          
       
        <asp:ScriptManager ID="ScriptManager1" runat="server" />     
         <input type="button" value=" 调用事件" id="button1" />       
         <script language="javascript" type="text/javascript">           
              var clientObject =
              {
                   text : "Hello ",   
                   OnClick : function(e, args)
                   {
                       alert(this.text + args + this.tail);
                   },
                   tail : "!"
              }            
              var onClickDelegate = Function.createCallback(Function.createDelegate(clientObject, clientObject.OnClick), "Rose Zhao");
              $addHandler($get("button1"), "click", onClickDelegate);
         script>
    div>
    form>
body >
23. Ajax String对象扩展方法String.format的使用
< body >
    <form id="form1" runat="server">
    <div>
       
        
          
       
        <asp:ScriptManager ID="ScriptManager1" runat="server" />              
         <script language="javascript" type="text/javascript">
             alert(String.format("Today is {0}.", new Date()));
              alert(String.localeFormat(" 今天是{0}" , new Date()));
         script>
    div>
    form>
body >
13). Ajax library中的客户端面向对象(OO)功能
24. 客户端注册命名空间, 定义接口, 类继承示例
< body >
    <form id="form1" runat="server">
    <div>
   
       
          
       
        <asp:ScriptManager ID="ScriptManager1" runat="server" ScriptMode="Debug">            
         asp:ScriptManager>   
        
         <script language=javascript>
        
             // 注册一个命名空间: "人类"
             Type.registerNamespace("Human");
            
             // 定义一个接口: IPerson
             Human.IPerson = function()
            {
                 throw Error.notImplemented();
            }
            Human.IPerson.prototype =
            {
                 FullName : function()
                 {
                     throw Error.notImplemented();
                 }           
            }
            Human.IPerson.registerInterface("Human.IPerson");
           
            // 定义一个类: Womenn , 并继承Human.IPerson
            Human.Womenn = function()
            {
                 this._FirstName;
                 this._LastName;
            }
            Human.Womenn.prototype =
            {
                 get_FirstName : function()
                 {
                     return this._FirstName;
                 },
                 set_FirstName : function(value)
                 {
                     this._FirstName = value;
                 },
             
                 get_LastName : function()
                 {
                     return this._LastName;
                 },                            
                 set_LastName : function(value)
                 {
                     this._LastName = value;
                 },
             
                 FullName : function()
                 {
                     return this._FirstName + " " + this._LastName;
                 }
            }
            Human.Womenn.registerClass("Human.Womenn", null,Human.IPerson);           
           
            // 使用定义的类
            //debugger;
            var Rose = new Human.Womenn();           
            // 注意这里不是这样写:Rose.set_LastName = "Jing";
            Rose.set_FirstName("Jing");            
            Rose.set_LastName("Zhao");           
            alert(Rose.FullName());
           
         script>
    div>
    form>
body >
14). Asp.net Ajax 中的多语功能
25. Asp.net 服务端使用全局和本地资源文件示例
前台页面代码:
< body >
    <form id="form1" runat="server">
   
   
           
       
       
           
   
    <div>
       
        <asp:Label ID="lbApple" runat="server">asp:Label>       
        <asp:Label ID="lbOrange" runat="server" Text="<%$ Resources:GlobalFruitsResource,Orange %>">asp:Label>
       
       
        <asp:Label ID="lbBanana" runat="server" meta:resourcekey="lblBanana">asp:Label>       
       
    div>
    form>
body >
后台页面代码:
public partial class _N_Global_and_Local_Resources__A_Asp_net_Resource_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // 获取全局资源文件
        this.lbApple.Text = Resources.GlobalFruitsResource.Apple;
    }
}
 
26. Asp.net 客户端使用全局和本地资源文件示例
前台页面代码:
< body >
    <form id="form1" runat="server">
    <div>
   
       
               
         
               
               
       
       
               
   
        <asp:ScriptManager runat="server" ID="sm" EnableScriptLocalization="true">
            <Scripts>
                <asp:ScriptReference Path="~/(N)Global and Local Resources/(26)Ajax Resource/FruitsResource.js" ResourceUICultures="zn-ch,en-US" />
            Scripts>
        asp:ScriptManager>
       
        <script language="javascript">
            alert(Fruits.Fruit.Pear);
        script>
       
    div>
    form>
body >
 
中文资源文件FruitsResource.js代码:
///
Type.registerNamespace("Fruits");
 
Fruits.Fruit =
{
    "Pear" : " 梨"
}
 
英文资源文件FruitsResource.en-US.js代码:
///
Type.registerNamespace("Fruits");
 
Fruits.Fruit =
{
    "Pear" : "Pear"
}
 
(三).教程下载
      http://www.cnblogs.com/Files/MVP33650/Asp.net%20Ajax(by%20ChengKing).rar
(四 ).推荐站点
1. http://www.asp.net/ajax/
2. http://www.cnblogs.com/JeffreyZhao/
 

你可能感兴趣的:(其他)