重要补充:
重要补充:
Ajax.dll 和 AjaxPro.dll 是两家不同的产品, 但用法很类似, 对于.net 1.1 和.net 2.0
需要不同的dll支持!!
Ajax.dll 官网: http://ajax.schwarz-interactive.de/csharpsample/default.aspx
AjaxPro.dll 官网: http://www.ajaxpro.info/
两者使用比较: ajax两组件之对比(ajax.dll,ajaxpro.dll) http://blog.csdn.net/nicewon/archive/2007/04/06/1554460.aspx
最近由于任务需要不得不重新接触.net2003 但是要使用到javascript,而又感觉.net代码很乱,不好跟JS交互,所以使用了Ajax.dll来帮助简化,以下是简单的总结,希望对大家有用!
简单流程:为了方便学习,顺便把官网给的例子中的关键源程序贴出来以方便学习:
- 测试环境:
- XP + .Net 2003 + Ajax.dll 5.7.22.2
- 1> .net项目添加引用 Ajax.dll
- 2> 在 web.config 文件里按如下格式添加配置:
- (说明:这里是指定一个虚拟路径以动态给出js文件下载地址)
- <configuration>
- <system.web>
- <httpHandlers>
- <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
- </httpHandlers>
- ...
- <system.web>
- </configuration>
- 3> 在一个类(任意类)里实现一个Ajax方法:
- using System;
- namespace zhAjax{
- public class AjaxTest{
- public AjaxTest(){}
- [Ajax.AjaxMethod]//Ajax方法
- public int sum(int a, int b){
- return a+b;
- }
- }
- }
- 4> 在一个aspx页面的codebehind代码中的Page_Load()方法中加入如下代码:
- private void Page_Load(object sender, System.EventArgs e){
- //在当前页面中注册服务器端的Ajax方法,注册的类是zhAjax.AjaxTest
- //其中zhAjax是命名空间,AjaxTest是类名。
- Ajax.Utility.RegisterTypeForAjax(typeof(zhAjax.AjaxTest));
- }
- 5> 在aspx页面里包含自己用到的JS文件,两个内容如下:
- aspx文件:
- <%@ Page language="c#" Codebehind="Z.aspx.cs" AutoEventWireup="false" Inherits="zhAjax.WebForm2" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
- <HTML> <HEAD>
- <title>WebForm2</title>
- <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
- <meta name="CODE_LANGUAGE" Content="C#">
- <meta name="vs_defaultClientScript" content="JavaScript">
- <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
- <script type=text/javascript language=javascript src='js.js' ></script>
- <!-- 注意:自己引入的JS标签一定要有单独的结尾标签</script>,否则将会出现
- ajax_request为定义的现象,应为IE6将其其后的html都当作javascript了,
- 同时要注意自己的Javascript不要出现任何错误 -->
- </HEAD>
- <body MS_POSITIONING="GridLayout">
- <form id="Form1" method="post" runat="server">
- A: <input id=a size=15 ><br >
- B: <input id=b size=15 ><br >
- SUM: <input id=sum size=15 ><br >
- <input type=button value='计算' οnclick="myFunc()" ><br >
- </form>
- </body>
- </HTML>
- js文件:js.js
- function myFunc(){
- AjaxTest.sum(
- document.getElementById("a").value,
- document.getElementById("b").value,
- callback
- );
- }
- function callback(ret){
- document.getElementById("sum").value = ret.value;
- }
Methods.CS
default.js
- using System;
- using System.Web;
- namespace CSharpSample
- {
- /// <summary>
- /// Summary description for Methods.
- /// </summary>
- public class DemoMethods
- {
- [Ajax.AjaxMethod]
- public static string Test1(string firstName, string familyName, string email, string comment)
- {
- return "Hello " + firstName + " " + familyName + "<br>Thank you for your comment ("
- + DateTime.Now.ToString() + "):<br><b>" + System.Web.HttpUtility.HtmlEncode(comment).Replace("/r", "<br>") + "</b>.";
- }
- [Ajax.AjaxMethod]
- public string Test2(DateTime d)
- {
- d = d.AddDays(1);
- return "The next day will be " + d.ToLongDateString() + ".";
- }
- [Ajax.AjaxMethod]
- public System.Data.DataSet Test3()
- {
- System.Data.DataSet ds = new System.Data.DataSet();
- System.Data.DataTable dt = new System.Data.DataTable();
- dt.Columns.Add("Country", typeof(System.String));
- ds.Tables.Add(dt);
- System.Data.DataRow row;
- // fill sample data (i.e. can be replaced with database query)
- row = ds.Tables[0].NewRow();
- row["Country"] = "Germany";
- dt.Rows.Add(row);
- row = ds.Tables[0].NewRow();
- row["Country"] = "Austria";
- dt.Rows.Add(row);
- row = ds.Tables[0].NewRow();
- row["Country"] = "Switzerland";
- dt.Rows.Add(row);
- row = ds.Tables[0].NewRow();
- row["Country"] = "France";
- dt.Rows.Add(row);
- row = ds.Tables[0].NewRow();
- row["Country"] = "Bavaria ;)";
- dt.Rows.Add(row);
- return ds;
- }
- [Ajax.AjaxMethod]
- public void Test4()
- {
- throw new System.Security.SecurityException("This user does not have access rights on this resource.");
- }
- [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
- public void Test5(string value)
- {
- HttpContext.Current.Session["test"] = value;
- }
- [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
- public string Test6()
- {
- if(HttpContext.Current.Session["test"] != null)
- return (string)HttpContext.Current.Session["test"];
- return "First set the value...";
- }
- [Ajax.AjaxMethod]
- public void Test7()
- {
- int c = 0;
- do
- {
- System.Threading.Thread.Sleep(1000);
- c++;
- }
- while(c < 10);
- }
- [Ajax.AjaxMethod]
- public int Test8()
- {
- Random r = new Random(System.DateTime.Now.Second);
- return r.Next(0, 100);
- }
- [Ajax.AjaxMethod]
- public System.Collections.Specialized.StringCollection Test9()
- {
- System.Collections.Specialized.StringCollection s = new System.Collections.Specialized.StringCollection();
- s.Add("Michael");
- s.Add("Hans");
- return s;
- }
- [Ajax.AjaxMethod]
- public object[] Test10()
- {
- object[] o = new object[3];
- o[0] = "Michael";
- o[1] = DateTime.Now;
- o[2] = true;
- return o;
- }
- [Ajax.AjaxMethod]
- public System.Collections.ArrayList Test11()
- {
- System.Collections.ArrayList a = new System.Collections.ArrayList();
- a.Add("Michael");
- a.Add(DateTime.Now);
- a.Add(true);
- Person p1 = new Person();
- p1.FirstName = "Michael";
- SpecialPerson p2 = new SpecialPerson(); // will be inherit from Person
- p2.FirstName = "Tanja";
- p2.Comment = "My comment for this person!";
- a.Add(p1);
- a.Add(p2);
- return a;
- }
- [Ajax.AjaxMethod]
- public Person Test12()
- {
- // Create your own class like you have done it before.
- // See Person class at end of this file!
- Person p = new Person();
- p.FirstName = "Michael";
- p.FamilyName = "Schwarz";
- p.Age = 28;
- Person mj = p.NewChild();
- mj.FirstName = "Marc Julain";
- mj.Age = 3;
- Person jo = p.NewChild();
- jo.FirstName = "Jan Oliver";
- jo.Age = 1;
- p.Children = new Person[2];
- p.Children[0] = mj;
- p.Children[1] = jo;
- // Return the object without any change on the source code.
- return p;
- }
- [Ajax.AjaxMethod]
- public NewsTicker Test13()
- {
- NewsTicker[] nt = new NewsTicker[10];
- #region Build some examples (will be stored in a database or xml file)
- nt[0] = new NewsTicker("Ajax.NET Library", "http://ajax.schwarz-interactive.de", 4);
- nt[1] = new NewsTicker("Google Search", "http://www.google.com", 2);
- nt[2] = new NewsTicker("It is now " + DateTime.Now.ToString(), "http://ajax.schwarz-interactive.de", 4);
- nt[3] = new NewsTicker("ASP.NET Weblogs", "http://weblogs.asp.net/mschwarz", 3);
- nt[4] = new NewsTicker("Free Ajax.NET Wrapper", "http://weblogs.asp.net/mschwarz", 4);
- nt[5] = new NewsTicker("New C# examples online!", "http://ajax.schwarz-interactive.de", 3);
- nt[6] = new NewsTicker("PC-Topp.NET Demo", "http://demo.pctopp.com", 2);
- nt[7] = new NewsTicker("NEW Ajax.NET Library", "http://ajax.schwarz-interactive.de", 4);
- nt[8] = new NewsTicker("Download ajax.dll", "http://ajax.schwarz-interactive.de", 2);
- nt[9] = new NewsTicker("Free Download!!", "http://ajax.schwarz-interactive.de", 2);
- #endregion
- Random r = new Random(System.DateTime.Now.Second);
- int i = r.Next(0, nt.Length -1);
- return nt[i];
- }
- [Ajax.AjaxMethod]
- public System.Data.DataSet Test15()
- {
- System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection("server=(local);uid=??;password=????;Initial Catalog=Northwind;");
- System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT TOP 10 * FROM Customers C INNER JOIN Orders O ON O.CustomerID = C.CustomerID", conn);
- System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd);
- System.Data.DataSet ds = new System.Data.DataSet();
- try
- {
- conn.Open();
- try
- {
- da.Fill(ds);
- }
- catch(Exception)
- {}
- finally
- {
- conn.Close();
- conn.Dispose();
- }
- }
- catch(Exception)
- {}
- return ds;
- }
- [Ajax.AjaxMethod]
- public System.Drawing.Bitmap Test16()
- {
- System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(200, 50);
- System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
- g.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Yellow), 0, 0, 199, 49);
- g.DrawString(DateTime.Now.ToString(), new System.Drawing.Font("Arial", 10), new System.Drawing.SolidBrush(System.Drawing.Color.Red), 10, 10);
- return bmp;
- }
- [Ajax.AjaxMethod]
- public int Test17(int[] i)
- {
- int r = 0;
- foreach(int ii in i)
- r += ii;
- return r;
- }
- [Ajax.AjaxMethod]
- public string Test18(string[] s)
- {
- string r = "";
- foreach(string ss in s)
- r += "<p>" + ss + "</p>/r/n";
- return r;
- }
- [Ajax.AjaxMethod]
- public System.Web.UI.HtmlControls.HtmlSelect Test19(string car)
- {
- System.Web.UI.HtmlControls.HtmlSelect control = new System.Web.UI.HtmlControls.HtmlSelect();
- switch(car)
- {
- case "VW":
- control.Items.Add("Golf");
- control.Items.Add("Passat");
- control.Items.Add("Beetle");
- control.Items.Add("Phaeton");
- break;
- case "Mercedes":
- control.Items.Add("S Class");
- control.Items.Add("E Class");
- control.Items.Add("A Class");
- control.Items.Add("M Class");
- break;
- case "Citroen":
- control.Items.Add("C3 Pluriel");
- control.Items.Add("C5 Break");
- control.Items.Add("C8");
- control.Items.Add("Berlingo");
- break;
- }
- return control;
- }
- [Ajax.AjaxMethod(30)]
- public System.DateTime Test20()
- {
- return DateTime.Now;
- }
- [Ajax.AjaxMethod]
- public System.Web.UI.HtmlControls.HtmlSelect Test21(System.Web.UI.HtmlControls.HtmlSelect select)
- {
- select.Items.Add("New option added at " + DateTime.Now);
- return select;
- }
- [Ajax.AjaxMethod]
- public System.Xml.XmlDocument Test22()
- {
- System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
- doc.LoadXml("<ROOT/>");
- doc.DocumentElement.InnerText = DateTime.Now.ToString();
- return doc;
- }
- }
- [Serializable]
- public class NewsTicker
- {
- public Guid ID = Guid.NewGuid();
- public NewsTicker(string text, string url, int duration)
- {
- this.Text = text;
- this.URL = url;
- this.Duration = duration;
- }
- public string Text;
- public string URL;
- public int Duration = 60;
- }
- [Serializable]
- public class Person // : System.Collections.CollectionBase
- {
- public string FirstName;
- public string FamilyName;
- public int Age = 0;
- public decimal Money = 200.5m;
- public Person NewChild()
- {
- Person p = new Person();
- p.FamilyName = FamilyName;
- return p;
- }
- public Person[] Children = null;
- #region CollectionBase Methods
- // public Person this[ int index ]
- // {
- // get{ return ((Person)List[index]); }
- // set{ List[index] = value; }
- // }
- //
- // public int Add(Person value)
- // {
- // return(List.Add(value));
- // }
- //
- // public int IndexOf(Person value)
- // {
- // return(List.IndexOf(value));
- // }
- //
- // public void Insert(int index, Person value)
- // {
- // List.Insert(index, value);
- // }
- //
- // public void Remove(Person value)
- // {
- // List.Remove(value);
- // }
- //
- // public bool Contains(Person value)
- // {
- // // If value is not of type Int16, this will return false.
- // return(List.Contains(value));
- // }
- //
- // protected override void OnInsert(int index, Object value)
- // {
- // if(value.GetType() != Type.GetType("CSharpSample.Person"))
- // throw new ArgumentException("value must be of type CSharpSample.Person.", "value");
- // }
- //
- // protected override void OnRemove(int index, Object value)
- // {
- // if(value.GetType() != Type.GetType("CSharpSample.Person"))
- // throw new ArgumentException("value must be of type CSharpSample.Person.", "value");
- // }
- //
- // protected override void OnSet(int index, Object oldValue, Object newValue)
- // {
- // if(newValue.GetType() != Type.GetType("CSharpSample.Person"))
- // throw new ArgumentException("newValue must be of type CSharpSample.Person.", "newValue");
- // }
- //
- // protected override void OnValidate(Object value)
- // {
- // if(value.GetType() != Type.GetType("CSharpSample.Person"))
- // throw new ArgumentException("value must be of type CSharpSample.Person.");
- // }
- #endregion
- }
- [Serializable]
- public class SpecialPerson : Person
- {
- public string Comment = "";
- }
- [Serializable]
- public class IAjaxObjectSource
- {
- public string Title = "";
- public string Filename = "";
- public IAjaxObjectSource(string title, string filename)
- {
- Title = title;
- Filename = filename;
- }
- }
- }
- function callback_test1(res)
- {
- document.getElementById("display1").innerHTML = res.value;
- }
- function test1()
- {
- DemoMethods.Test1(
- document.getElementById("firstName").value,
- document.getElementById("familyName").value,
- document.getElementById("email").value,
- document.getElementById("comment").value,
- callback_test1
- );
- }
- function callback_test2(res)
- {
- document.getElementById("display2").innerHTML = res.value;
- }
- function test2()
- {
- var d = null;
- try
- {
- d = new DateTime(
- document.getElementById("year").value,
- document.getElementById("month").value,
- document.getElementById("day").value,
- 0, 0, 0
- );
- DemoMethods.Test2(d, callback_test2);
- }
- catch(e)
- {
- alert("Error: " + e.description);
- }
- }
- function callback_test3(res)
- {
- if(res != null && res.value != null && res.value.Tables != 0 && res.value.Tables.length == 1)
- {
- var html = [];
- for(var i=0; i<res.value.Tables[0].Rows.length; i++)
- html[html.length] = "<option>" + res.value.Tables[0].Rows[i].Country + "</option>";
- document.getElementById("display3").innerHTML = "<select>" + html.join("") + "</select>";
- }
- }
- function test3()
- {
- DemoMethods.Test3(callback_test3);
- }
- function test4()
- {
- var res = DemoMethods.Test4();
- if(res.error != null) alert(res.error);
- }
- function test5()
- {
- DemoMethods.Test5(document.getElementById("sessionTest1").value);
- }
- function callback_test6(res)
- {
- document.getElementById("sessionTest2").value = res.value;
- }
- function test6()
- {
- DemoMethods.Test6(callback_test6);
- }
- function callback_test7(res)
- {
- alert("The server has finished the 10 seconds call, now!");
- }
- function test7()
- {
- DemoMethods.Test7(callback_test7);
- }
- function test8(ele)
- {
- DemoMethods.Test8(test8_callback, ele); // the server-side method has no arguments!
- }
- function test8_callback(res)
- {
- if(res.error == null && res.context != null)
- res.context.innerHTML = res.value;
- }
- function test11()
- {
- DemoMethods.Test11(test11_callback);
- }
- function test11_callback(res)
- {
- if(res.value[2]) // bolean
- alert(res.value[1].toLocaleString()); // date
- alert(res.value[3].FirstName + " + " + res.value[4].FirstName);
- }
- function test12()
- {
- DemoMethods.Test12(test12_callback);
- }
- function test12_callback(res)
- {
- var s = res.value.FirstName + " " + res.value.FamilyName + ":/r/n";
- for(var i=0; i<res.value.Children.length; i++)
- s += "/t" + res.value.Children[i].FirstName + "/r/n";
- alert(s);
- }
- function test13()
- {
- // call the Ajax.NET method on the server to get
- // a new news ticker object
- DemoMethods.Test13(test13_callback);
- }
- function test13_callback(res)
- {
- if(typeof(res.value) == 'object')
- {
- // display the news ticker
- document.getElementById('newsticker').innerHTML = '<a href="' + res.value.URL + '">' + res.value.Text + '</a>';
- window.setTimeout(test13, res.value.Duration * 1000);
- }
- }
- function test16()
- {
- DemoMethods.Test16(test16_callback);
- }
- function test16_callback(res)
- {
- if(typeof(res.value) == 'object')
- {
- document.getElementById("imageholder").innerHTML = '';
- document.getElementById("imageholder").appendChild(res.value);
- }
- }
- function test17(n)
- {
- // n will be a array of numbers/integer
- if(typeof(n) != 'object') return;
- alert(DemoMethods.Test17(n).value);
- }
- function test18()
- {
- alert(DemoMethods.Test18( ["aaaa","bbbb","ccc/"ccccc"] ).value);
- }
- function test19(ele, car)
- {
- HtmlControlUpdate('DemoMethods.Test19', 'dropDisplay', car);
- }
- function test20()
- {
- return DemoMethods.Test20().value;
- }
- function test21(controlHolderId, id)
- {
- HtmlControlUpdate('DemoMethods.Test21', controlHolderId, new HtmlControl(id));
- }
- window.attachEvent("onload", test13);