2.<head>區塊插入以下JavaScript
<script type="text/javascript">
function LookUpStock()
{
var lb = document.getElementById("ListBox1");
var product = lb.options[lb.selectedIndex].text;
CallServer(product,""); //呼叫CallCallServer的JavaScript
}
function ReceiveServerData(rValue) //rValue是後端傳來前端的值
{
document.getElementById("ResultsSpan").innerHTML = rValue; //顯示出來而已
}
</script>
3.後置程式碼實作ICallbackEventHandler
public partial class Default2 : System.Web.UI.Page,ICallbackEventHandler
{
protected ListDictionary catalog;
protected string returnValue;
protected void Page_Load(object sender, EventArgs e)
{
//下面第二個參數參數"args"是CallServer接收的參數
//第三個參數"ReceiveServerData"則是用戶端的function
string cbReference = Page.ClientScript.GetCallbackEventReference(this, "args", "ReceiveServerData", "context");
string callbackscript = "function CallServer(args,context){" + cbReference + "};";
//下面第二個參數"CallServer"可隨便打,只是個索引,
//第三個參數callbackscript則是要在前端註冊一個JavaScript的function
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackscript, true);
//以下只是幫listBox1加資料而已
catalog = new ListDictionary();
catalog.Add("螢幕", 42);
catalog.Add("筆記型電腦", 10);
catalog.Add("鍵盤", 23);
catalog.Add("滑鼠", 17);
catalog.Add("桌上型電腦", 37);
catalog.Add("硬碟", 76);
catalog.Add("燒錄機", 34);
catalog.Add("電源供應器", 21);
ListBox1.DataSource = catalog;
ListBox1.DataTextField = "key";
ListBox1.DataBind();
}
string ICallbackEventHandler.GetCallbackResult()
{
return returnValue;
}
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument) //前端傳回伺服器的資料
{
if (catalog[eventArgument] == null)
{
returnValue = "-1";
}
else
{
returnValue = catalog[eventArgument].ToString();
}
}
}
引用以下參考:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Specialized; //只是為了ListDictionary參考的,沒啥特別的
1.<body>區塊插入以下標籤
<form id="form1" runat="server">
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
<br />
<input id="Button1" type="button" value="button" onclick="LookUpStock()"/>
<br /><br />
<span id="ResultsSpan" runat="server"></span>
</form>
留言列表