zoukankan      html  css  js  c++  java
  • Ext.Net 1.2.0_Ext.net.DirectMethods 使用

    http://examples.ext.net/#/Events/DirectMethods/Overview/

    本文在几个月前写过一次,当时刚刚使用 Ext.Net,现在重新整理一下,说说自己的理解,并附上源代码。 本 Blog 的文章我可能因为翻译问题,代码问题,理解问题,表述问题等等,都会不定期的重新整理发一下。

    本文内容

    • DirectMethod 基础
    • 从 DirectMethod 返回一个字符串
    • 给 DirectMethod 传递多个参数
    • 调用 DirectMethod 静态方法,并返回一个字符串
    • 从静态 DirectMethod 返回一个自定义对象
    • 禁用 DirectMethod ClientProxy 的创建
    • 向代理函数传递 DirectMethod 配置

    DirectMethod 提供了一种直接在客户端 JavaScript 代码中调用服务器端 .Net 方法的功能。

    [DirectMethod] 属性来修饰服务器端 publicpublic static 属性的方法,会向客户端 JavaScript 代码“公开”服务器端方法。

    注意:服务器端方法必须用 publicpublic static 修饰符。

    这种调用服务器端方法往往很好用,可以解决很多动态创建控件和数据加载问题(例如,根据权限动态创建按钮),以及它们造成的页面呈现问题。

    例如,当页面很多控件都是动态时,每次刷新页面,Ext.Net 在获得数据后,都会自己重新按照它的式样呈现数据,此时可能报脚本错误。

    我经常遇到的情况是,Ext.Net.GridPanelExt.Net.Store 刷新问题。Ext.Net 的处理顺序是,先把数据加载到 Store 里(如 Store.DataSource=new DataTable(); Store.DataBind(); ),然后再用 GridPanel 呈现。因此,如果你的顺序是反的。先为 GridPanel 动态创建行或组按钮,再调用 GridPanel.Render(),之后,向 Store 绑定数据,就很可能出现刷新问题。

    假设你只使用了 Page_Load 事件进行页面初始化,并在初始化时进行 if(!IsAjaxRequest) {…} 判断。如果 debug 程序,那么,Ext.Net 框架在页面第一次初始化时,IsAjaxRequest==false,表明这第一次不是 Ajax 请求。当你对页面进行操作,并调用了服务器端方法时,无论是通过 Ext.Net 何种方式调用,之后就全是 Ajax 请求,即 IsAjaxRequest==true,此时,与 ASP.NET 程序相比,你会发现很多方法都会执行,而且有些方法会反复执行很好几次。这就是 Ajax 程序的特点——多次向服务器端请求资源,只要它需要。并且,这些请求都是局部刷新页面。

    所以,我通常是,在页面初始化时,如 Page_Load,尽量先将页面的整体情况呈现给客户,即 if(!IsAjaxRequest) {…} 里的代码。然后,根据用户对页面的动作,通过直接调用服务器端方法,获得数据,呈现给用户。

    事前想好,如何呈现你的页面给用户其实重要。能很大程度减少页面刷新次数、页面响应时间,提升页面性能。

    DirectMethod 基础

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

    <%@ Page Language="C#" %>
     
    <%@ 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 runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:         [DirectMethod]
       3:         public void SetTimeStamp()
       4:         {
       5:             this.Label1.Text = DateTime.Now.ToLongTimeString();
       6:             this.Label1.Element.Highlight();
       7:         }
       8:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <ext:ResourceManager ID="ResourceManager1" runat="server" />
        <ext:Button ID="Button1" runat="server" Text="Click Me" Icon="Lightning">
            <Listeners>
                <Click Handler="Ext.net.DirectMethods.SetTimeStamp();" />
            </Listeners>
        </ext:Button>
        <br />
        <ext:Label ID="Label1" runat="server" Text='<%# DateTime.Now.ToLongTimeString() %>'
            Format="Server Time: {0}" />
        </form>
    </body>
    </html>

    运行结果:

    DirectMethod 基础

    图1 DirectMethod 基础

    说明

    • Button1 客户端事件里,调用服务器端方法 SetTimeStamp 来更新 Label1 控件,并高亮显示。
    • 另外,在 Ext.Net,当第一次请求页面时(此时为回发),IsAjaxRequestfalse,之后为 true,因为之后的请求是 Ajax 请求。

    从 DirectMethod 返回一个字符串

    DirectMethod 会返回任何类型的对象。该对象序列化后,作为 result 参数发送给在 DirectMethod 中配置的回调函数 successDirectMethod 方法成功时的客户端处理函数)。

    <%@ Page Language="C#" %>
     
    <%@ 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 runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:         [DirectMethod]
       3:         public string GetTimeStamp()
       4:         {
       5:             return DateTime.Now.ToLongTimeString();
       6:         }
       7:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <ext:ResourceManager ID="ResourceManager1" runat="server" />
        <ext:Button ID="Button2" 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>

    运行结果:

    从 DirectMethod 返回一个字符串

    图2 从 DirectMethod 返回一个字符串

    说明

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

    给 DirectMethod 传递多个参数

    如果服务器端 [DirectMethod] 方法要求参数,那么也要客户端 DirectMethod 传递给它相应的参数。

    本例中,如果服务器端要求两个参数:stingint,那么在客户端也要传递两个可靠的参数给服务器端的 [DirectMethod] 方法。

    <%@ Page Language="C#" %>
     
    <%@ 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 runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:         [DirectMethod]
       3:         public void LogCompanyInfo(string name, int count)
       4:         {
       5:             string template = string.Concat("{0} has approximately {1} employees.");
       6:             string[] employees = new string[4] { "1-5", "6-25", "26-100", "100+" };
       7:  
       8:             this.Label1.Text = string.Format(template, name, employees[count]);
       9:         }
      10:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <ext:ResourceManager ID="ResourceManager1" runat="server" />
        <ext:Button ID="Button1" runat="server" Text="Click Me">
            <Listeners>
                <Click Handler="Ext.net.DirectMethods.LogCompanyInfo('Ext.NET, Inc.', 0);" />
            </Listeners>
        </ext:Button>
        <br />
        <ext:Label ID="Label1" runat="server" />
        </form>
    </body>
    </html>

    运行结果:

    给 DirectMethod 传递多个参数

    图3 给 DirectMethod 传递多个参数

    调用 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//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 runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:         [DirectMethod]
       3:         public static string GetTimeStamp()
       4:         {
       5:             return DateTime.Now.ToLongTimeString();
       6:         }
       7:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <ext:ResourceManager ID="ResourceManager1" runat="server" />
        <ext:Button 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>

    运行结果:

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

    图4 调用 DirectMethod 静态方法,并返回一个字符串

    说明

    • Button1 客户端事件调用服务器端静态方法 GetTimeStamp(),获得服务器端当前时间。

    注意:服务器端静态方法 GetTimeStamp() 中不能访问页面中的 Web 控件。

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

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

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

    <%@ Page Language="C#" %>
     
    <%@ 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 runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:         // Define Customer Class
       3:         public class Customer
       4:         {
       5:             public int ID { get; set; }
       6:             public string FirstName { get; set; }
       7:             public string LastName { get; set; }
       8:             public string Company { get; set; }
       9:             public Country Country { get; set; }
      10:             public bool Premium { get; set; }
      11:         }
      12:         // Define Country Class
      13:         public class Country
      14:         {
      15:             public string Name { get; set; }
      16:         }
      17:         [DirectMethod]
      18:         public static Customer GetCustomer()
      19:         {
      20:             return new Customer()
      21:             {
      22:                 ID = 99,
      23:                 FirstName = "Peter",
      24:                 LastName = "Smith",
      25:                 Company = "CompanyX, LLC.",
      26:                 Premium = true,
      27:                 Country = new Country { Name = "Canada" }
      28:             };
      29:         }
      30:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <ext:ResourceManager ID="ResourceManager1" runat="server" />
        <ext:Button ID="Button1" runat="server" Text="Click Me" Icon="Lightning">
            <Listeners>
                <Click Handler="
                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);                    
                        Ext.Msg.alert('Customer', msg);
                    }
                });" />
            </Listeners>
        </ext:Button>
        </form>
    </body>
    </html>

    运行结果:

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

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

    说明

    • 定义两个类 CustomerCountryCountry 聚合在 Customer
    • 服务器端静态方法 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] 都可以被直接调用。

    Ext.net.DirectMethod.request() 方法原型如下:

    request ( string methodName , [Object options] ) : void
    Calls the server-side [DirectMethod] as specified in the methodName parameter.
    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//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 runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:         [DirectMethod(ClientProxy = ClientProxy.Ignore)]
       3:         public string GetTimeStamp()
       4:         {
       5:             return DateTime.Now.ToLongTimeString();
       6:         }
       7:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <ext:ResourceManager ID="ResourceManager1" runat="server" />
        <ext:Button ID="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 ClientProxy 的创建

    图6 禁用 DirectMethod ClientProxy 的创建

    向代理函数传递 DirectMethod 配置

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

    <%@ Page Language="C#" %>
     
    <%@ 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 runat="server">
        <title></title>
     
        <script runat="server">
       1:  
       2:         [DirectMethod]
       3:         public string LogMessage(string msg)
       4:         {
       5:             // Log the message somewhere...
       6:             return msg;
       7:         }
       8:     
    </script>
     
    </head>
    <body>
        <form id="form1" runat="server">
        <ext:ResourceManager ID="ResourceManager1" runat="server" />
        <ext:Button ID="Button4" 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>

    运行结果:

    向代理函数传递 DirectMethod 配置

    图7 向代理函数传递 DirectMethod 配置

    下载 Demo

  • 相关阅读:
    根分区/tmp满了,卸载home添加给根分区
    Docker容器技术教程
    使用vscode访问和编辑远程服务器文件
    使用 VS Code 远程连接Linux服务器告别xshell
    Docker安装参考文档记录
    yolov5在Centos系统上部署的环境搭建
    YOLOV5四种网络结构的比对
    k8s部署kube-state-metrics组件
    Kubernetes集群部署Prometheus和Grafana
    Prometheus介绍
  • 原文地址:https://www.cnblogs.com/liuning8023/p/2460629.html
Copyright © 2011-2022 走看看