zoukankan      html  css  js  c++  java
  • 模板化的“请等待”按钮和模板控件介绍

    1. 介绍 本文介绍了模 板化ASP的构造。网络控制,工作作为一个请等待按钮。使用c#和ASP。,您将看到如何创建模板化控件和添加特定功能。 有时候,您需要在提交页面时执行一些耗时的任务,例如在按钮单击事件期间。有时,表单的验证可以请求一些对数据库的调用,或远程调用、Web服务……要通知用户服务器正在执行一些耗时的操作,最好显示一条等待消息。 我看到一些文章重新创建了一个添加属性的按钮,显示一个消息。但是这个演示对我不合适。所以我决定创建一个完整的模板,可以通过模板功能进行定制。 2. 要得到的结果 我想在我的ASP中有这样的东西。NET页面: 隐藏,复制Code

    <Test:PleaseWaitButtonID="PWB"runat="server">
        <PleaseWaitMessageTemplate>
            <divstyle="500px;color:green;border:1px solid red;text-align:center">
                <div>Please wait a moment, </div>
                <div>we are checking your informations ...</div>
                <asp:Imagerunat="server"ImageUrl="wait.gif"/>
            </div>
        </PleaseWaitMessageTemplate>
    </Test:PleaseWaitButton>

    然后,我们有了按钮,以及定义“请等待”消息图形可视化的位置。 要看起来像一个真正的按钮,我们需要在按钮单击时定义一个事件处理程序。我们希望能够用text属性定制按钮的文本。 在表单中,我们通常希望使用ASP。网络验证。然后,该按钮需要检查此验证并定义(如果需要)ValidationGroup属性。 隐藏,复制Code

    <Test:PleaseWaitButtonID="PWB"runat="server"OnClick="ClickButton"ValidationGroup="myGroup"Text="Please Click">
        <PleaseWaitMessageTemplate>
            <divstyle="500px;color:green;border:1px solid red;text-align:center">
                <div>Please wait a moment, </div>
                <div>we are checking your informations ...</div>
                <asp:Imagerunat="server"ImageUrl="wait.gif"/>
            </div>
        </PleaseWaitMessageTemplate>
    </Test:PleaseWaitButton>

    3.创建模板按钮 首先,您必须从Control继承并实现INamingContainer。您还必须定义ParseChildren(true)属性。 隐藏,复制Code

    [System.Security.Permissions.PermissionSet(
      System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    [ParseChildren(true)]
    [DefaultProperty("Text")]
    public class PleaseWaitButton : Control, INamingContainer
    {
    }

    3.1。ITemplate属性 这就是您所需要的全部:拥有一个template属性。PersistenceMode用于告诉解析器该属性作为内部属性持续存在。TemplateContainer在这里没有使用,它是用于绑定类型的。 隐藏,复制Code

    private ITemplate _pleaseWaitMessageTemplate = null;
    
    [Browsable(false), DefaultValue(null), 
        PersistenceMode(PersistenceMode.InnerProperty), 
        TemplateContainer(typeof(TemplateItem))]
    public ITemplate PleaseWaitMessageTemplate
    {
        get { return _pleaseWaitMessageTemplate; }
        set { _pleaseWaitMessageTemplate = value; }
    }

    我们还需要定义TemplateItemp类。 隐藏,复制Code

    // TemplateItem should implement INamingContainer
    [ToolboxItem(false)]
    public class TemplateItem : Control, INamingContainer
    {
    }

    4.2。控件的创建 我们将重写CreateChildControls方法来创建一个包含我们的控件的面板。在这个面板中,如果用户定义了一个模板,我们会实例化它(作为一个TemplateItem)。如果没有定义模板,则创建一个带有默认消息的默认LiteralControl。 在那之后,我们添加了一个按钮,定义了一个点击处理程序,并将文本属性设置为文本属性。 使用CSS样式,我们将面板设置为不显示任何样式。面板外的按钮总是可见的。 隐藏,收缩,复制Code

    protected override void CreateChildControls()
    {
        Controls.Clear();
        // Create an hidden panel
        Panel panelMessage = new Panel();
        panelMessage.Attributes["style"] = "display:none";
        if (PleaseWaitMessageTemplate != null)
        {
            // if a template is defined, use it
            TemplateItem templateItem = new TemplateItem();
            PleaseWaitMessageTemplate.InstantiateIn(templateItem);
            panelMessage.Controls.Add(templateItem);
        }
        else
        {
            // else, create a default ugly message
            panelMessage.Controls.Add(new LiteralControl("Plesae Wait ..."));
        }
    
        // Button is created with Text property
        // and a click handler
        Button boutonValidation = new Button();
        boutonValidation.Text = Text;
        boutonValidation.Click += b_Click;
    
        // Then add panel and button
        Controls.Add(panelMessage);
        Controls.Add(boutonValidation);
    }

    4.3。属性的创建 如所见,我们需要保存一个ValidationGroup属性和一个Text属性。如果没有定义文本,我们使用默认的“OK”值。我们还定义了一个单击事件。为了确保控件的创建,让我们重写控件属性并调用EnsureChildControls()(如果需要,它将调用CreateChildControls)。 隐藏,复制Code

    [Bindable(true), Category("Behavior"), Description("Validation group")]
    public string ValidationGroup
    {
        get { return (string)ViewState["ValidationGroup"] ?? string.Empty; }
        set { ViewState["ValidationGroup"] = value; }
    }
    
    [Bindable(true), Category("Appearance"), 
      DefaultValue("OK"), Description("Button's text")]
    public string Text
    {
        get { return (string)ViewState["Text"] ?? "OK"; }
        set { ViewState["Text"] = value; }
    }
    
    private event EventHandler _clickHandler;
    public event EventHandler Click
    {
        add { _clickHandler += value; }
        remove { _clickHandler -= value; }
    }
    
    public override ControlCollection Controls
    {
        get { EnsureChildControls(); return base.Controls; }
    }

    4.4。验证 我们必须要求验证页面(使用页面)。验证方法)。如果定义了ValidationGroup,则要求对该组进行验证。 隐藏,复制Code

    private void b_Click(object sender, EventArgs e)
    {
        // manual validation
        if (!string.IsNullOrEmpty(ValidationGroup))
            Page.Validate(ValidationGroup);
        else
            Page.Validate();
        // Fire the user-define click event, if defined
        if (_clickHandler != null)
            _clickHandler(sender, e);
    }

    4.4。客户端JavaScript 在客户端,我们必须做两件事: 客户端验证并显示/隐藏请等待消息 这是用JavaScript完成的。如果验证是OK或NOK,我们将使用面板的显示样式(在HTML中表示为div)。 因此,让我们在呈现阶段添加一些JavaScript,以在客户端按钮单击事件上调用一个特定的JavaScript函数(参见注释)。 但首先,我们必须找到面板的clientId。 隐藏,收缩,复制Code

    protected override void OnPreRender(EventArgs e)
    {
        // we look for the panel and set an ID
        // warning : this operation can't be done
        // in CreateChildControls, it would have been too earl
        Panel panelMessage = null;
        foreach (Control control in Controls)
        {
            if (control is Panel)
            {
                control.ID = ID + "_waiting";
                panelMessage = (Panel) control;
            }
        }
        // When panel founded, look for the button,
        // and add a clientside function 
        //(with panel clientId as parameters)
        if (panelMessage != null)
        {
            foreach (Control control in Controls)
            {
                if (control is Button)
                {
                    ((Button) control).OnClientClick = 
                        string.Format("checkForm('{0}')", panelMessage.ClientID);
                }
            }
        }
        base.OnPreRender(e);
    }

    在呈现时,根据客户机验证的结果(使用Page_ClientValidate方法完成客户机验证),创建管理显示的java脚本函数。 隐藏,收缩,复制Code

    protected override void Render(HtmlTextWriter writer)
    {
        // script client-side creation :
        // If there's a validation group,
        // call validation function with the group as parameters
        // else without parameters
        string validationGroupParameters = string.IsNullOrEmpty(ValidationGroup) ? 
                string.Empty : string.Format("'{0}'", ValidationGroup);
    
        // if validation is OK, display panel (and waiting message)
        // if validation NOK, hide panel and return false
        string script = @"function getObj(id)
    {
        var o;
        if (document.getElementById)
        {
            o = document.getElementById(id).style;
        }
        else if (document.layers)
        {
            o = document.layers[id];
        }
        else if (document.all)
        {
            o = document.all[id].style;
        }
        return o;
    }
    function setDisplay(id)
    {
        var o = getObj(id);
        if (o)
        {
            o.display = 'block';
        }
    }
    function unsetDisplay(id)
    {
        var o = getObj(id);
        if (o)
        {
            o.display = 'none';
        }
    }
    function checkForm(divWaiting)
    {
        try
        {
            if (!Page_ClientValidate(" + validationGroupParameters + @"))
            {
                unsetDisplay(divWaiting);
                return false;
            }
        }
        catch (e) {}
        setDisplay(divWaiting);
    }";
        Page.ClientScript.RegisterStartupScript(GetType(), 
                "javascriptButton", script, true);
    
        base.Render(writer);
    }

    4. 创建使用此按钮的默认页面 4.1。没有验证 只需定义模板控件和模板属性。如果需要,添加一个按钮单击处理程序。 隐藏,复制Code

    <Test:PleaseWaitButtonID="PWB"runat="server"OnClick="ClickButton">
        <PleaseWaitMessageTemplate>
            <divstyle="500px;color:green;border:1px solid red;text-align:center">
                <div>Please wait a moment, </div>
                <div>we are checking your informations ...</div>
                <asp:Imagerunat="server"ImageUrl="wait.gif"/>
            </div>
        </PleaseWaitMessageTemplate>
    </Test:PleaseWaitButton>

    在代码隐藏中,模拟要执行的耗时任务… 隐藏,复制Code

    protected void ClickButton(object sender, EventArgs e)
    {
        Thread.Sleep(2000);
    }

    4.2。与验证 4.2.1。准备没有验证组 让我们定义一个文本框,并使用RequiredFieldValidator控件添加客户端验证和使用CustomValidator控件添加服务器端验证。 隐藏,复制Code

    <asp:TextBoxrunat="server"ID="aTextBox"/>
    <asp:RequiredFieldValidatorrunat="server"ControlToValidate="aTextBox"ErrorMessage="Field should have a value"Display="dynamic"/>
    <asp:CustomValidatorrunat="server"OnServerValidate="ValidateFunction"Display="dynamic"ErrorMessage="Value should be ABC"/>
    
    protected void ClickButton(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Thread.Sleep(2000);
            Response.Write("<br/>Informations are OK<br/>");
        }
    }
    
    protected void ValidateFunction(object source, ServerValidateEventArgs args)
    {
        args.IsValid = aTextBox.Text == "ABC";
    }

    4.2.2。与验证组 你也可以尝试一个验证组,像这样: 隐藏,收缩,复制Code

    <asp:TextBoxrunat="server"ID="aTextBox"/>
    <asp:RequiredFieldValidatorrunat="server"ControlToValidate="aTextBox"ErrorMessage="Field should have a value"Display="dynamic"ValidationGroup="myGroup"/>
    <asp:CustomValidatorrunat="server"OnServerValidate="ValidateFunction"Display="dynamic"ErrorMessage="Value should be ABC"ValidationGroup="myGroup"/>
    
    <Test:PleaseWaitButtonID="PWB"runat="server"OnClick="ClickButton"ValidationGroup="myGroup">
        <PleaseWaitMessageTemplate>
            <divstyle="500px;color:green;border:1px solid red;text-align:center">
                <div>Please wait a moment, </div>
                <div>we are checking your informations ...</div>
                <asp:Imagerunat="server"ImageUrl="wait.gif"/>
            </div>
        </PleaseWaitMessageTemplate>
    </Test:PleaseWaitButton>
    
    protected void ClickButton(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Thread.Sleep(2000);
            Response.Write("<br/>Informations are OK<br/>");
        }
    }
    
    protected void ValidateFunction(object source, ServerValidateEventArgs args)
    {
        args.IsValid = aTextBox.Text == "ABC";
    }

    5. 预览 6. 结论 我希望你会发现这个模板按钮有用,也许学习如何在ASP中创建一个模板控件。净与c#。验证是一个关键点,在ASP中非常有用。网络页面。了解如何利用验证API进行验证也会非常有用。 如果您在本文、源代码或其他信息中看到错误,请给我发送评论。 本文转载于:http://www.diyabc.com/frontweb/news383.html

  • 相关阅读:
    03 http请求协议与响应协议
    02 web应用程序
    Django web框架目录
    01 http协议
    Django框架
    Bootstrap栅格系统
    bootstrap介绍和引入
    Python中日志logging模块
    Python 装饰器实现单列模式
    Python 如何理解可更改元组中的可变序列
  • 原文地址:https://www.cnblogs.com/Dincat/p/13443962.html
Copyright © 2011-2022 走看看