C# .NET AJAX無刷新技術

下載一個.net Ajax開發包,該開發包包括ASP2.0和目前ASP1.1版使用的Ajax,詳細地址參見http://ajax.schwarz-interactive.de/,接下來,開始。

1. 新建一個項目,在引用中添加引用Ajax.dll,Ajax.dll位於下載的壓縮包裏面。

2.建立HttpHandler,在web.config裏面加上


<configuration>

<system.web>

<httpHandlers>

<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />

</httpHandlers>

<system.web>

</configuration>



3.新建一個類DemoMethods,這個類實現獲取客戶端MAC地址:

using System;

using System.Web;

namespace AjaxSample

{

/**//// <summary>

/// Summary description for Methods.

/// </summary>

public class DemoMethods

{

[Ajax.AjaxMethod]

public string GetCustomerMac(string clientIP) //這裏輸入客戶端IP,這個函數知識測試用,你也可以寫一個其他的簡單一點的函數代替

{

string mac = "";

System.Diagnostics.Process process = new System.Diagnostics.Process();

process.StartInfo.FileName = "nbtstat";

process.StartInfo.Arguments = "-a "+clientIP;

process.StartInfo.UseShellExecute = false;

process.StartInfo.CreateNoWindow = true;

process.StartInfo.RedirectStandardOutput = true;

process.Start();

string output = process.StandardOutput.ReadToEnd();

int length = output.IndexOf("MAC Address = ");

if(length>0)

{

mac = output.Substring(length+14, 17);

}

process.WaitForExit();

return mac.Replace("-", "").Trim();

}

}}

4.寫javascript,新建一個名爲default.js文件如下

function GetMac()

{

var clientIP="192.168.0.1";

//document.getElementById("Mac").value=DemoMethods.GetCustomerMac(clientIP).value

alert(DemoMethods.GetCustomerMac(clientIP).value);

}

5.在某個Aspx頁面放上一個html 的button

在頁面上<head>中引用default.js :

<script language="javascript" src="default.js"></script>

在INPUT的onclick事件中加上

οnclick="javascript:GetMac()"

<INPUT style="Z-INDEX: 101; LEFT: 392px; POSITION: absolute; TOP: 176px" type="button"

value="客戶端獲取IP" οnclick="javascript:GetMac();">

6.在page頁面的Page_Load事件中加上

private void Page_Load(object sender, System.EventArgs e)

{

// 在此處放置用戶代碼以初始化頁面

Ajax.Utility.RegisterTypeForAjax(typeof(AjaxSample.DemoMethods));

}

注意:typeof(AjaxSample.DemoMethods)中,AjaxSample是命名空間,DemoMethods是要包含要調用方法的類,即上面第3步.新建類DemoMethods

7.修改Global.asax的Application_Start事件,設置Ajax的HandlerPath :

protected void Application_Start(Object sender, EventArgs e)

{

Ajax.Utility.HandlerPath = "ajax";

}

運行看看效果。是不是沒有刷新就在服務器端取到客戶端的MAC地址?

需要注意的是:該版本的.net Ajax需要手工在中Global.asax加上Ajax.Utility.HandlerPath = "ajax"; 配置文件web.config必須加上HttpHandler的配置信息!

該開發包的新版本還沒有來得及體驗,估計新版本中會方便一些,可能會去掉手動的設置Global.asax的Application_Start事件中加上Ajax.Utility.HandlerPath = "ajax";以及其他麻煩的設置!
發佈了35 篇原創文章 · 獲贊 3 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章