EXT.NET_DirectMethod 使用

DirectMethod 可以从客户端JavaScript代码调用服务器端.NET方法。

用[DirectMethod] 属性修饰服务器端的public或 public static 方法,会向客户端JavaScript代码开放服务器端方法。否则,客户端JavaScript不能调用服务器端方法。



DirectMethod 基础

下面代码演示DirectMethod 一个简单的例子,更新<ext:Label> 控件。

<%@ Page Language="C#" %>
 
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net"TagPrefix="ext" %>
<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 
    <scriptrunat="server">
       protected void Page_Load(object sender, EventArgs e)
       {
           if (!X.IsAjaxRequest)
           {
                this.Label1.DataBind();
           }
       }
       [DirectMethod]
       public void SetTimeStamp()
       {
           this.Label1.Text = string.Concat("Server Time: ", DateTime.Now.ToLongTimeString());
           this.Label1.Element.Highlight();
       }
    </script>
 
</head>
<body>
    <formid="form1" runat="server">
    <ext:ResourceManagerID="ResourceManager1" runat="server" />
    <ext:ButtonID="Button1" runat="server" Text="Click Me" Icon="Lightning">
       <Listeners>
           <Click Handler="Ext.net.DirectMethods.SetTimeStamp();" />
       </Listeners>
    </ext:Button>
    <ext:LabelID="Label1" runat="server" Format="Server Time:{0}" Text='<%#DateTime.Now.ToLongTimeString() %>' />
    </form>
</body>
</html>

说明

1,在Page_Load事件里,如果不是一个Ajax请求,则初始化Label1控件。当页面第一次被加载时,IsAjaxRequest为false,之后为true;

2,在Button1客户端事件里,调用服务器端方法SetTimeStamp,更新Label1控件,并高亮显示。


从DirectMethod 返回一个字符串

DirectMethod会返回任何类型的对象。这个对象被序列化成JSON。被系列化的这个对象作为result参数发送给在DirectMethod配置中配置的 success函数。

<%@ Page Language="C#" %>
 
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net"TagPrefix="ext" %>
<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 
    <scriptrunat="server">
       [DirectMethod]
       public string GetTimeStamp()
       {
           return DateTime.Now.ToLongTimeString();
       }
    </script>
 
</head>
<body>
    <formid="form1" runat="server">
    <ext:ResourceManagerID="ResourceManager1" runat="server" />
    <ext:ButtonID="Button1" runat="server" Text="Click Me" Icon="Lightning">
       <Listeners>
           <Click Handler="
           Ext.net.DirectMethods.GetTimeStamp({
                success: function (result) {
                    Ext.Msg.alert('ServerTime', result);
                }
           });" />
       </Listeners>
    </ext:Button>
    </form>
</body>
</html>

说明

在Button1客户端事件中,Ext.net.DirectMethods.GetTimeStamp(…) 是客户端调用服务器端方法 GetTimeStamp,success 是 Ext.net.DirectMethods的配置,也就是说,当服务器端方法成功返回时,客户端需要执行的操作。在本例中,如果服务器端方法 GetTimeStamp() 成功返回服务器端当前时间,则客户端弹出这个时间警告。


给DirectMethod 传递多个参数

如果服务器端[DirectMethod] 方法要求参数,那么也要创建客户端DirectMethod,并传递两个参数给它。

本例,如果服务器端要求一个sting和int参数,那么也要传递给客户端函数两个可靠的参数。

<%@ Page Language="C#" %>
 
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net"TagPrefix="ext" %>
<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 
    <scriptrunat="server">
       [DirectMethod]
       public void LogCompanyInfo(string name, int count)
       {
           string template = string.Concat("{0} has approximately {1}employees.");
           string[] employees = new string[4] { "1-5", "6-25", "26-100","100+" };
 
           this.Label1.Text = string.Format(template, name, employees[count]);
       }
    </script>
 
</head>
<body>
    <formid="form1" runat="server">
    <ext:ResourceManagerID="ResourceManager1" runat="server" />
    <ext:PanelID="Panel1" runat="server" Title="CompanyInformation" AutoHeight="true"
       Width="350" Padding="5" Frame="true" Layout="Form">
       <Items>
           <ext:TextField ID="TextField1" runat="server" FieldLabel="CompanyName" AllowBlank="false"
                AnchorHorizontal="100%"/>
           <ext:ComboBox ID="ComboBox1" runat="server" FieldLabel="#of Employees" AnchorHorizontal="100%">
                <Items>
                    <ext:ListItem Text="1-5"Value="0" />
                    <ext:ListItem Text="6-25"Value="1" />
                    <ext:ListItem Text="26-100"Value="2" />
                    <ext:ListItem Text="101+"Value="3" />
                </Items>
           </ext:ComboBox>
       </Items>
       <Buttons>
           <ext:Button ID="Button1" runat="server" Text="Submit"Icon="Lightning">
                <Listeners>
                    <Click Handler="Ext.net.DirectMethods.LogCompanyInfo(#{TextField1}.getValue(),#{ComboBox1}.getValue());" />
                </Listeners>
           </ext:Button>
       </Buttons>
    </ext:Panel>
    <br/>
    <ext:LabelID="Label1" runat="server" Text="Write CompanyInformation Here" />
    </form>
</body>
</html>

调用DirectMethod 静态方法,并返回一个字符串(Super Fast + Best Performance)

当调用一个 public 服务端方法,默认情况下,在执行整个页面生命期时,这个方法可以访问页面上所有 Web 控件。

而带static 的[DirectMethod] 方法,不会执行页面生存期,并且不能访问页面 Web 控件。这减少了处理开销,优化了性能。

<%@ Page Language="C#" %>
 
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net"TagPrefix="ext" %>
<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 
    <scriptrunat="server">
       [DirectMethod]
       public static string GetTimeStamp()
       {
           return DateTime.Now.ToLongTimeString();
       }
    </script>
 
</head>
<body>
    <formid="form1" runat="server">
    <ext:ResourceManagerID="ResourceManager1" runat="server" />
    <ext:ButtonID="Button1" runat="server" Text="Click Me" Icon="Lightning">
       <Listeners>
           <Click Handler="
                   Ext.net.DirectMethods.GetTimeStamp({
                        success: function(result) {
                           Ext.Msg.alert('Server Time', result);
                        }
                    });" />
       </Listeners>
    </ext:Button>
    </form>
</body>
</html>

说明

Button1客户端事件调用服务器端静态方法GetTimeStamp(),获得服务器端当前时间。注意:服务器端静态方法GetTimeStamp()中不能访问页面中的 Web 控件。


从静态 DirectMethod 返回一个自定义对象

DirectMethod 可以返回任何类型的对象。下面例子创建并返回一个 Customer 对象。

Customer 对象被序列化成 JSON,返回给客户端。在 DirectMethod配置中,result参数就是从服务器端返回的对象。

<%@ Page Language="C#" %>
 
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net"TagPrefix="ext" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 
    <scriptrunat="server">
        publicclass Customer
        {
            publicint ID { get; set; }
            publicstring FirstName { get; set; }
            publicstring LastName { get; set; }
            publicstring Company { get; set; }
            publicCountry Country { get; set; }
            publicbool Premium { get; set; }
        }
        publicclass Country
        {
            publicstring Name { get; set; }
        }
        [DirectMethod]
        publicstatic Customer GetCustomer()
        {
            returnnew Customer()
            {
               ID = 99,
               FirstName = "Peter",
               LastName = "Smith",
               Company = "CompanyX, LLC.",
               Premium = true,
                Country = new Country { Name = "Canada"}
           };
        }
    </script>
 
</head>
<body>
    <form id="form1"runat="server">
    <ext:ResourceManagerID="ResourceManager1" runat="server" />
    <ext:ButtonID="Button1" runat="server" Text="Click Me" Icon="Lightning">
        <Listeners>
            <ClickHandler="
                   Ext.net.DirectMethods.GetCustomer({
                        success : function(customer) {
                            var template = 'ID: {0}{6} Name : {1} {2}{6} Company : {3}{6} Country : {4}{6} Premium Member :{5}',
                                msg =String.format(template,
                                       customer.ID,
                                       customer.FirstName,
                                        customer.LastName,
                                       customer.Company,
                                       customer.Country.Name,
                                       customer.Premium,
                                        '<br /><br/>');
                           
                           Ext.Msg.alert('Customer', msg);
                        }
                   });" />
        </Listeners>
    </ext:Button>
    </form>
</body>
</html>

说明

1,  定义两个类 Customer和Country,Country 聚合在 Customer;

2,  服务器端静态方法 GetCustomer() 创建 Customer 对象返回给客户端。注意:客户端如何访问对象 Customer。


禁用 DirectMethod ClientProxy 的创建

当服务器端方法添加[DirectMethod] 属性,默认情况下,将会在客户端的Ext.net.DirectMethods 创建一个相同名字、接受相同参数的 JavaScript函数。

例如,如果创建一个名为GetTimeStamp服务器端方法,那么在客户端,也会创建一个Ext.net.DirectMethods.GetTimeStamp 的 JavaScript 函数。

有种情况,当开发者创建一个DirectMethod,但是想隐藏相应的客户端JavaScript函数。你可以在某个DirectMethod设置ClientProxy.Ignore属性,从而忽略创建相应的客户端JavaScript函数。

如果DirectMethod设置为ClientProxy.Ignore,将不会创建相应的客户端代理函数(client-side proxy function),但是DirectMethod仍然可以被调用。DirectMethod代理函数是围绕底层Ext.net.DirectMethod.request()函数的封装。

通过配置Ext.net.DirectMethod.request()函数,即便没有客户端代理函数,任何服务器端DirectMethod都可以被直接调用。

request ( string methodName , [Object options] ) : void
methodName参数规定调用服务器端 [DirectMethod] 方法名。
Parameters:
methodName : String
The server-side Method name to call.
options : Object
(optional) An object containing configuration properties. This options object may contain any of the following properties, or options as defined in Ext.Ajax.request.
success : Function
The JavaScript function to invoke on successful response from the DirectMethod. The "result" parameter is passed to the success function.
failure : Function
The JavaScript function to invoke if a failure response is returned from the DirectMethod. The "errorMessage" parameter is passed to the success function.
specifier : String
The server-side Method access specifier, options inlcude ("public", "static"). The specifier of "public" is the default value and does not need to be explicitly set. If the server-side Method is a static Method, the specifier options must be set to "static".
method : String
The type of http request to make, options include ("POST", "GET"). The method of "POST" is the default value.
url : String
A custom url to call the DirectMethod from. The DirectMethod does not need to be configured on the "Parent Page". If no url is provided, the request options will use the <form>'s action attribute. If the action attribute is empty, the request options will use the window.location.href value. If the window.location.href value ends with a forward-slash ("/"), the IIS web server may not be able to process the "POST" request. Under this scenario, you must set the "method" options property to "GET".
control : String
The ID of the UserControl which contains the DirectMethod. An DirectMethod can be configured within a .ascx file and called from a Parent .aspx Page.
timeout : Number
The timeout in milliseconds to be used for requests. (defaults to 30000)
eventMask : Object
(optional) An EventMask options object. This options object may contain any of the following properties:
showMask : Boolean
true to show mask (defaults to false).
msg : String
The text to display in a centered loading message box (defaults to 'Working...').
msgCls : String
The CSS class to apply to the loading message element (defaults to "x-mask-loading")
target : String
The target element to apply the mask to, options include ("page", "customtarget"). If "customtarget", the customTarget configuration option should be set.
customTarget : String
The id of the target element, or a instance of the target element.
minDelay : Number
The minimum amount of time to display the mask (defaults to 0). Setting the minDelay provides and minimum amount of time to display a message to the user before removing mask and executing success, failure and/or callback functions.
Returns:
void
<%@ Page Language="C#" %>
 
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net"TagPrefix="ext" %>
<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 
    <scriptrunat="server">
       [DirectMethod(ClientProxy = ClientProxy.Ignore)]
       public string GetTimeStamp()
       {
           return DateTime.Now.ToLongTimeString();
       }
    </script>
 
</head>
<body>
    <formid="form1" runat="server">
    <ext:ResourceManagerID="ResourceManager1" runat="server" />
    <ext:ButtonID="Button1" runat="server" Text="Click Me" Icon="Lightning">
       <Listeners>
           <Click Handler="Ext.net.DirectMethod.request(
                    'GetTimeStamp',
                    {
                        success: function(result) {
                           Ext.Msg.alert('Message', result);
                        }
                    });" />
       </Listeners>
    </ext:Button>
    </form>
</body>
</html>


向代理函数传递 DirectMethod 配置

DirectMethod 配置对象可以被作为最后一个参数传递给任何DirectMethod 代理函数。

<%@ Page Language="C#" %>
 
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net"TagPrefix="ext" %>
<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 
    <scriptrunat="server">
       [DirectMethod]
       public string LogMessage(string msg)
       {
           return msg;
       }
    </script>
 
</head>
<body>
    <formid="form1" runat="server">
    <ext:ResourceManagerID="ResourceManager1" runat="server" />
    <ext:ButtonID="Button3" runat="server" Text="Click Me" Icon="Lightning">
       <Listeners>
           <Click Handler="
           Ext.net.DirectMethods.LogMessage('Hello World', {
                            success: function(result) {
                               Ext.Msg.alert('Message', result);
                            },
                            eventMask: {
                                showMask: true,
                               minDelay: 500
                            }
                        });" />
       </Listeners>
    </ext:Button>
    </form>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值