asp.net中使用php常用的jquery等類庫來實現ajax不是很容易。因為
asp.net的機制已經被封裝了,依靠內部的viewstate,如果硬用js修改了控制項的值,跟他的viewstate對不上,而這些控制項又是不可修改的,將對程式造成安全性困擾,後台擷取值也是一個麻煩。
另外,asp.net的控制項也封裝了html控制項,使用js操作不是這麼直接。
根據Surance( http://www.fltek.com.cn/)研究發現,在asp.net中,有3種方法使用ajax比較簡單。算是ms的一個補償方案來的。
一個是PageMethod,一個是使用ICallbackEventHandler,還有一個是用ms內建的ajax控制項。
分別舉例說明,
以下例子要實現的功能為:
在頁面有一個div,一個按鈕。點擊按鈕要調用後台方法擷取一個時間,然後將時間寫入div。要求頁面不重新整理
另外有個背景按鈕,點擊此按鈕,取到儲存後的值
1.PageMehtod
第一步,建立一個asp.net的ajax網站(或者建立普通網站後修改webconfig)
第二步,在頁面建立控制項:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
<div id="show" runat="server">aaaa
</div>
<asp:HiddenField ID="HiddenField1" runat="server" />
<input type="button" value="1111" onclick="myFun()" id="Button2" />
<asp:Button ID="Button1" runat="server" Text="getValue" OnClick="Button1_Click" />
第三步,js
<script>
function myFun()
{
PageMethods.GetDate('a',myCallBack)
}
function myCallBack(result)
{
var di = document.getElementById("HiddenField1");
di.value=result;
var di = document.getElementById("show");
di.innerHTML=result;
}
</script>
第四步,後台代碼
注意,這個方法必須是靜態方法,必須是寫入以下特性。
因此這個方法不可以直接存取頁面的值
[System.Web.Services.WebMethod]
public static DateTime GetDate(string a)
{
return DateTime.Now;
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)this.DataList1.DataSource;
Response.Write(dt.Rows.Count);
}
2.使用ICallbackEventHandler
第一步同上
第二步,頁面實現介面
public partial class Default2 : System.Web.UI.Page, ICallbackEventHandler
第三步,建立控制項
<form id="form1" runat="server">
<div id="show">
</div>
<input type="button" onclick="CallServer()" value="CallServer"></input>
第四步,
寫入js
<script type="text/javascript">
function CallServer()
{
var product = "1";
<%= ClientScript.GetCallbackEventReference(this, "product", "ReceiveServerData",null)%>;
}
function ReceiveServerData(rValue)
{
alert(rValue);
var di = document.getElementById("show");
di.innerHTML=rValue;
}
</script>
第五步,
後台代碼
聲明變數: public string CallBackValue;
介面方法:
public string GetCallbackResult()
{
return CallBackValue + ",ok";
}
public void RaiseCallbackEvent(string eventArgument)
{
this.CallBackValue = eventArgument;
}
說明:RaiseCallbackEvent是實際做事的方法
GetCallbackResult是執行完動作回調的方法。
可以修改控制項的值。
先執行背景回調方法,後執行前台js的回調方法
可以使用RenderControl等類,來將asp.net控制項輸出為html
可以在RaiseCallbackEvent中switchargument,看看是什麼地方傳來的,以便調用不同的函數。