А>Возник такой вопрос, как на время выполнения сделать кнопку disable.
А>Просто запись на диск файла размером 30 метров занимает определенное время, как можно узнать, что файл успешно закончился записываться на диск, а затем сделать enable button.

M>>>> <input onclick="var self = this; window.setTimeout( function (){self.disabled = true;}, 10 )"  type="submit" value="lala" name="ff" />

Сим>>>Но в этом случае, все равно, если страница невалидна, то кнопка дизейблится
M>>Да ты прав, в 2.0 они поменяли скрипты которые для кнопок вызываются... надо исследовать, буру таймаут

OE>в 1.1 тот же эффект


1.

btn_submit.Attributes["onclick"] = "if (typeof(Page_ClientValidate) == 'function') { Page_ClientValidate();if (!Page_IsValid) return false; }; var self = this; window.setTimeout( function (){self.disabled = true;}, 10 );";

Но будет некий излишек, в виде повторной валидации.

2. модифицировать onclick уже на клиенте например в body.onload

<script>
        var root_ = this;
        function on_load()
        {
           var btn = document.getElementById("<%=Button2.ClientID%>");
           var old_onclick_handler = btn.onclick;
           btn.onclick = function ()
           {
            if ( old_onclick_handler )
                old_onclick_handler();
            
            if ( "Page_IsValid" in  root_ ) 
                {                
                if ( Page_IsValid )
                    window.setTimeout( function (){btn.disabled = true;}, 10 );
                else 
                    return false;
                }
            else
                window.setTimeout( function (){btn.disabled = true;}, 10 );
           }
        }
    </script>

3. но правильнее — унаследоваться от Button
и переопределить метод AddAttributesToRender так, чтобы генерился правильный onclick statement

protected override void AddAttributesToRender(HtmlTextWriter writer)
{
      if (this.Page != null)
      {
            this.Page.VerifyRenderingInServerForm(this);
      }
      writer.AddAttribute(HtmlTextWriterAttribute.Type, "submit");
      writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);
      writer.AddAttribute(HtmlTextWriterAttribute.Value, this.Text);
      if (((this.Page != null) && this.CausesValidation) && (this.Page.Validators.Count > 0))
      {
            string text1 = Util.GetClientValidateEvent(this.Page);
            if (base.HasAttributes)
            {
                  string text2 = base.Attributes["onclick"];
                  if (text2 != null)
                  {
                       text1 = text2 + text1;
                        base.Attributes.Remove("onclick");
                  }
            }
            writer.AddAttribute(HtmlTextWriterAttribute.Onclick, text1);
            writer.AddAttribute("language", "javascript");
      }
      base.AddAttributesToRender(writer);
}

в выделеной строке валидация приписывается _после_ пользовательского.

полный текст со всеми тремя примерами

ASPX

<%@ Page language="c#" Codebehind="DisableOnPostBack.aspx.cs" AutoEventWireup="false" Inherits="Test_app.DisableOnPostBack.DisableOnPostBack" %>
<%@Register tagPrefix ="meta" namespace="Test_app.DisableOnPostBack" Assembly="Test_app" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
    <title>DisableOnPostBack</title>
<meta content="Microsoft Visual Studio .NET 7.1" name=GENERATOR>
<meta content=C# name=CODE_LANGUAGE>
<meta content=JavaScript name=vs_defaultClientScript>
<meta content=http://schemas.microsoft.com/intellisense/ie5 name=vs_targetSchema>
<script>
        var root_ = this;
        function on_load()
        {
           var btn = document.getElementById("<%=Button2.ClientID%>");
           var old_onclick_handler = btn.onclick;
           btn.onclick = function ()
            {
              if ( old_onclick_handler )
                 old_onclick_handler();
            
              if ( "Page_IsValid" in  root_ ) 
              {                
                if ( Page_IsValid )
                    window.setTimeout( function (){btn.disabled = true;}, 10 );
                else 
                    return false;
              }
              else
                window.setTimeout( function (){btn.disabled = true;}, 10 );
            }
        }
</script>
</HEAD>
<body onload=on_load()>
<form id=Form1 method=post runat="server">

        <asp:textbox id=TextBox1 runat="server"></asp:TextBox>
        <asp:requiredfieldvalidator id=RequiredFieldValidator1 runat="server" ErrorMessage="dsfgsdgfsdfgs" ControlToValidate="TextBox1">fdsgsdfgs</asp:RequiredFieldValidator><BR>
    
        <asp:Button Runat="server" ID="Button1" Text="Button1"/>
        <asp:Button runat="server" id="Button2" Text="Button2"></asp:Button>    
        <meta:ButttonSelfDisabledOnClick id="Button3" runat=server Text="Button3" />
        
        </FORM>
  </body>
</HTML>

C#

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace Test_app.DisableOnPostBack
{
   /// <summary>
   /// Summary description for DisableOnPostBack.
   /// </summary>
   public class DisableOnPostBack : System.Web.UI.Page
   {
      protected System.Web.UI.WebControls.TextBox TextBox1;
      protected System.Web.UI.WebControls.Button Button2;
      protected System.Web.UI.WebControls.Button Button1;
      protected ButttonSelfDisabledOnClick Button3;
      protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
    
      private void Page_Load(object sender, System.EventArgs e)
      {
    Button1.Attributes["onclick"] = "if (typeof(Page_ClientValidate) == 'function') { Page_ClientValidate();if (!Page_IsValid) return false; }; var self = this; window.setTimeout( function (){self.disabled = true;}, 10 );";
      }

      #region Web Form Designer generated code
      override protected void OnInit(EventArgs e)
      {
    //
    // CODEGEN: This call is required by the ASP.NET Web Form Designer.
    //
    InitializeComponent();
    base.OnInit(e);
      }
        
      /// <summary>
      /// Required method for Designer support - do not modify
      /// the contents of this method with the code editor.
      /// </summary>
      private void InitializeComponent()
      {    
     this.Button1.Click += new System.EventHandler(this.Button_Click);
         this.Button2.Click += new System.EventHandler(this.Button_Click);
         this.Button3.Click += new System.EventHandler(this.Button_Click);
         this.Load += new System.EventHandler(this.Page_Load);

      }
      #endregion

      private void Button_Click(object sender, System.EventArgs e)
      {
         Thread.Sleep( 3000 );
        
      }

   }

   public class ButttonSelfDisabledOnClick: Button
   {
      protected override void AddAttributesToRender(HtmlTextWriter writer)
      {
         if (this.Page != null)
         {
            this.Page.VerifyRenderingInServerForm(this);
         }
         writer.AddAttribute(HtmlTextWriterAttribute.Type, "submit");
         writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);
         writer.AddAttribute(HtmlTextWriterAttribute.Value, this.Text);
         if (((this.Page != null) && this.CausesValidation) && (this.Page.Validators.Count > 0))
         {
            string text1 = GetClientValidateEvent(this.Page);
            if (  Attributes.Count > 0 )
            {
               string text2 = base.Attributes["onclick"];
               if (text2 != null)
               {
                  text1 = text2 + text1;
                  base.Attributes.Remove("onclick");
               }
            }
               writer.AddAttribute(HtmlTextWriterAttribute.Onclick, text1);
               writer.AddAttribute("language", "javascript");
         }
            base.AddAttributesToRender(writer);
      }
        
      internal static string GetClientValidateEvent(Page page)
      {
         return "if (typeof(Page_ClientValidate) == 'function') { Page_ClientValidate();if (!Page_IsValid) return false; } var self = this; window.setTimeout( function (){self.disabled = true;}, 10 ); ";
      }
   }
}

Тест примеров подправлен для FAQ по результатам дальнейшего обсуждения
... << RSDN@Home 1.1.4 beta 6a rev. 436>>
Автор: mogadanez    Оценить