自定义Button防止重复提交
由于网速问题,用户总是迫不及待的多次点击提交按钮,从而造成多次提交。以下通过自定义Button控件,来解决此问题。
原理:点击按钮后,通过设置其disabled属性为true来达到目的。
自定义Button控件核心代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | protected override void AddAttributesToRender(HtmlTextWriter writer) { System.Text.StringBuilder ClientSideEventReference = new System.Text.StringBuilder(); //是否实现页面验证 if ((( this .Page != null ) && this .CausesValidation) && ( this .Page.Validators.Count > 0)) { ClientSideEventReference.Append( "if (typeof(Page_ClientValidate) == 'function'){if (Page_ClientValidate() == false){return false;}}" ); } //是否提示提交 if ( this .ShowMessageBox) { ClientSideEventReference.Append( "if (!confirm('" + this .WarningText + "')){return false}" ); } //是否使用Button的OnClientClick属性进行js验证 if ( this .OnClientClick != "" ) { ClientSideEventReference.Append( "if(!" + OnClientClick + ") { return false;}" ); } ClientSideEventReference.AppendFormat( "this.value = '{0}';" , ( string ) this .ViewState[ "afterSubmitText" ]); ClientSideEventReference.Append( "this.disabled = true;" ); ClientSideEventReference.Append( this .Page.ClientScript.GetPostBackEventReference( this , string .Empty)); writer.AddAttribute(HtmlTextWriterAttribute.Onclick, ClientSideEventReference.ToString(), true ); base .AddAttributesToRender(writer); } |
使用自定义Button范例核心代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | < pre class="brush:csharp">< script type="text/javascript"> function Validate() { var txt = document.getElementById('<%=txtContext.ClientID %>'); if(txt.value == "") { alert('文本框不能为空!'); txt.focus(); return false; } return true; } </ script > < cc1:ClickOnceButton ID="btnAdd" runat="server" Text="提交" OnClick="btnAdd_Click" OnClientClick="Validate()" /> </ pre > < 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" /> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?