由于网速问题,用户总是迫不及待的多次点击提交按钮,从而造成多次提交。以下通过自定义Button控件,来解决此问题。
原理:点击按钮后,通过设置其disabled属性为true来达到目的。
自定义Button控件核心代码:
01 |
protected override void AddAttributesToRender(HtmlTextWriter writer) |
03 |
System.Text.StringBuilder ClientSideEventReference = new System.Text.StringBuilder(); |
06 |
if ((( this .Page != null ) && this .CausesValidation) && ( this .Page.Validators.Count > 0)) |
08 |
ClientSideEventReference.Append( "if (typeof(Page_ClientValidate) == 'function'){if (Page_ClientValidate() == false){return false;}}" ); |
12 |
if ( this .ShowMessageBox) |
14 |
ClientSideEventReference.Append( "if (!confirm('" + this .WarningText + "')){return false}" ); |
18 |
if ( this .OnClientClick != "" ) |
20 |
ClientSideEventReference.Append( "if(!" + OnClientClick + ") { return false;}" ); |
23 |
ClientSideEventReference.AppendFormat( "this.value = '{0}';" , ( string ) this .ViewState[ "afterSubmitText" ]); |
24 |
ClientSideEventReference.Append( "this.disabled = true;" ); |
27 |
ClientSideEventReference.Append( this .Page.ClientScript.GetPostBackEventReference( this , string .Empty)); |
29 |
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, ClientSideEventReference.ToString(), true ); |
30 |
base .AddAttributesToRender(writer); |
使用自定义Button范例核心代码:
01 |
< PRE class = brush :csharp>< script type = "text/javascript" > |
04 |
var txt = document.getElementById('<%=txtContext.ClientID %>'); |
15 |
< cc1:ClickOnceButton ID = "btnAdd" runat = "server" Text = "提交" OnClick = "btnAdd_Click" OnClientClick = "Validate()" /> |
17 |
< STRONG >注意事项</ STRONG >:如果通过设置OnClientClick属性来进行验证时,OnClientClick属性所对应的属性值即:js函数不能带符号“;”< BR > Example:错误写法: OnClientClick="Validate();" 正确写法: OnClientClick="Validate()" |
美中不足:查看页面源码是发现有两个onclick事件(如下),OnClientClick属性对应的onclick事件没有起到作用。望路过高手提出解决意见!
1 |
<input onclick= "if(!Validate()) { return false;}this.value = '正在提交,请稍候...';this.disabled = true;__doPostBack('btnAdd','')" type= "submit" name= "btnAdd" value= "提交" onclick= "Validate();" id= "btnAdd" /> |
源码下载