我们对在前台触发一个客户端事件,来操作界面元素,已经很熟悉,但这属于静态脚本范畴。往往有些时候,我们还需要动态脚本,也就是说,脚本在执行过程中需要的变量,是从服务器端获得的,那么X.Js.Call方法的作用,就是将服务器端变量传给客户端脚本,并执行脚本。
例子
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExtNetXJsCall._Default" %> <%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script type="text/javascript"> var myAlert = function() { alert("警告"); } var myAlert2 = function(id, val) { var txtField = Ext.getCmp(id); txtField.setValue(val); alert(txtField.getValue()); } </script> </head> <body> <form id="form1" runat="server"> <ext:ResourceManager ID="ResourceManager1" runat="server" /> <ext:Button ID="Button1" runat="server" OnDirectClick="Button1_Click" Text="X.Js.Call一个参数的"> </ext:Button> <ext:Button ID="Button2" runat="server" OnDirectClick="Button2_Click" Text="X.Js.Call两个参数的"> </ext:Button> <ext:TextField ID="TextField1" runat="server" Text=""> </ext:TextField> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Ext.Net; namespace ExtNetXJsCall { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, DirectEventArgs e) { X.Js.Call("myAlert"); } protected void Button2_Click(object sender, DirectEventArgs e) { string[] paras = new string[] { this.TextField1.ClientID, "警告" }; X.Js.Call("myAlert2", paras); } } }
说明
1,Button2将服务器端变量传给脚本方法“myAlert2”,脚本根据这个值设置页面控件,并显示。