摘要:利用 ajax 註冊javascript 來進行非同步傳輸值
########################### 介 面 端 #############################
目前股價:<asp:Label ID="price1" runat="server"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" onclientclick="CallServer('','');return false;" />
########################### 程式端 ###################################
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
public partial class 非同步處理 : System.Web.UI.Page, ICallbackEventHandler
{
string strResult;
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager csm = Page.ClientScript; //取得目前頁面的ClientScriptManage
string s = csm.GetCallbackEventReference(this, "args", "ReceiveServerData", "context");
string strcallback = "function CallServer(args,context){" + s + ";};"; //編寫javascript語法
csm.RegisterClientScriptBlock(this.GetType(), "jsCallServer", strcallback, true); //註冊javascript語法
LoadScript(); //註冊javascript function ReceiveServerData(args, context) 方法
}
protected void LoadScript()
{
//註冊javaScript方法
//接收ServerData傳回值
string yString =
"function ReceiveServerData(args, context) {"+
"document.getElementById('"+price1.ClientID+"').innerText = args; }";
Page.ClientScript.RegisterStartupScript(this.GetType(), "jsScript", yString, true); ;
}
public string GetCallbackResult()
{
//「傳回」以控制項為目標之回呼事件的結果
return strResult;
}
public void RaiseCallbackEvent(string eventArgument)
{
//「處理」以控制項為目標的回呼事件。
Random r = new Random();
double StockPrice = r.NextDouble() * r.Next(1, 101);
// Response.Write("xx"+StockPrice);
strResult = StockPrice.ToString("C"); //轉成貨幣格式
}
}