关于.net的异步刷新机制 ICallbackEventHandler
时间:2011-04-27 来源:PrettyIce
最近在做一个项目,有一个页面用到异步刷新,因为不想用updatepanel处理,就想到了.net自带的ICallbackEventHandler接口,在这里简单的对照msdn写了一个列子。
既然要异步,那么肯定要手动在前台写部分js了,既然是交互,那么传值这一步是少不了的了,显然首先要有一个调取的页面元素值得方法
- function LookUpStock() {
- var lb = document.getElementById("ListBox1");
- var product = lb.options[lb.selectedIndex].text;
- CallServer(product, "");
- }
那么既然是异步更新数据,那么修改后的值肯定是js进行操作的了,这里就添加了一个返回值的js方法
- function ReceiveServerData(rValue) {
- document.getElementById("ResultsSpan").innerHTML = rValue;
- }
前台页面的html内容如下:
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head id="Head1" runat="server">
- <title>Client Callback Example</title>
- <script type="text/ecmascript">
- function LookUpStock() {
- var lb = document.getElementById("ListBox1");
- var product = lb.options[lb.selectedIndex].text;
- CallServer(product, "");
- }
- function ReceiveServerData(rValue) {
- document.getElementById("ResultsSpan").innerHTML = rValue;
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:ListBox ID="ListBox1" Runat="server"></asp:ListBox>
- <br />
- <br />
- <button type="Button" onclick="LookUpStock()">Look Up Stock</button>
- <br />
- <br />
- Items in stock: <span id="ResultsSpan" runat="server"></span>
- <br />
- </div>
- </form>
- </body>
- </html>
在后台:
- public partial class Default2 : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
- {
- protected System.Collections.Specialized.ListDictionary catalog;
- protected String returnValue;//用来得到返回值
- protected void Page_Load(object sender, EventArgs e)
- {
- String cbReference =
- Page.ClientScript.GetCallbackEventReference(this,
- "arg", "ReceiveServerData", "context");//添加页面回传触发操作
- String callbackScript;
- callbackScript = "function CallServer(arg, context)" +
- "{ " + cbReference + ";}";
- Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
- "CallServer", callbackScript, true);
- //注册前台CallServer方法,方法内容就是 callbackScript
- catalog = new System.Collections.Specialized.ListDictionary();
- catalog.Add("monitor", 12);
- catalog.Add("laptop", 10);
- catalog.Add("keyboard", 23);
- catalog.Add("mouse", 17);
- ListBox1.DataSource = catalog;
- ListBox1.DataTextField = "key";
- ListBox1.DataBind();
- }
- //这里是继承自ICallbackEventHandler的方法,将页面的值传入处理
- public void RaiseCallbackEvent(String eventArgument)
- {
- if (catalog[eventArgument] == null)
- {
- returnValue = "-1";
- }
- else
- {
- returnValue = catalog[eventArgument].ToString();
- }
- }
- //这里是继承自ICallbackEventHandler的方法
- //将处理后的值返回,供页面使用
- public String GetCallbackResult()
- {
- return returnValue;
- }
- }
本文出自 “小白龙” 博客,请务必保留此出处http://sunhoy.blog.51cto.com/2993277/555097
相关阅读 更多 +