ASP.NET Button 的 disable & Validator 結合問題 ?

ASP.NET Button 的 disable & Validator 結合問題 ?

前陣子看到討論區有這方面的問題,如下:

像是「存檔」、「更新資料」這一類的 button 都會搭配 validator control 作資料驗證
不過有時網路不夠快或是頁面執行速度較慢會讓 user 覺得網頁當掉而再「多」按一下 button
這樣有時會導致資料重覆送出,所以我想讓 button 按下後有一種效果,
若通過 validator 驗證,則會一併將 button disable 起來,
若沒有通過 validator 驗證,button 則是仍然有效。

小弟就做一個範例介紹如何完成這樣的功能...c#

ButtonDemo.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ButtonDemo.aspx.cs" Inherits="ButtonDemo" %>

<!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>ButtonDemo</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
                ErrorMessage="不可為空白"></asp:RequiredFieldValidator>
            <br />
            <asp:Button ID="Button2" runat="server" Text="送出" OnClientClick="return ConfirmMe(this)"
                OnClick="Button2_Click" />
        </div>
    </form>
</body>
</html>

<script type="text/javascript">
function ConfirmMe(btn)
{
   if(Page_ClientValidate())
   {
        btn.disabled="disabled";
        document.forms[0].__EVENTTARGET.value = btn.name;
        document.forms[0].__EVENTARGUMENT.value = '';
        document.forms[0].submit();
   }
   else
   {
        return false;
   }
}
</script>
 

ButtonDemo.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class ButtonDemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

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

}

執行結果:

沒輸入時,會有驗證文字出現

有輸入時,會將Button給disable,防止重覆點選

參考網址:

http://www.dotblogs.com.tw/puma/archive/2008/03/26/2313.aspx

http://www.blueshop.com.tw/board/show.asp?subcde=BRD20080410142742P4B&fumcde=