asp.net服务器控件button先执行js再执行后台的方法
生活随笔
收集整理的这篇文章主要介绍了
asp.net服务器控件button先执行js再执行后台的方法
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
关于button这个服务器控件,我一直想减少它向服务器提交数据。那些检测,还是在客户端实现就好了。
这就需要javascript,但是我发现仅仅有javascript还是不够的。button服务器控件的单击事件叫“onClick”,
所以javascript就无法使用这个事件。因为重名了。我想实现的是单击button的时候,先执行客户端的javascript代码,然后再执行后台事件。
如果使用的是html控件,就不存在这种问题了。但是,我就是想实现服务器控件的这一功能,有时候服务器控件也是很好用的。
先给aspx页面增加一个服务器控件button
?
| 1 | </asp:button> |
在页面初始化的时候,给button这个服务器控件增加一个客户端事件。也就是在Page_Load()这个方法里面加一句代码:
?
| 1 2 3 4 5 | if (!IsPostBack) { //给button1添加客户端事件 btnSave.Attributes.Add("OnClick", "return UserAddVerify()"); } |
UserAddVerify 是js端实现的函数,主要用来检测数据的有效性。
?
| 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 32 33 34 35 36 37 38 | function UserAddVerify() { var userName = document.getElementById("TxtUserName").value; var password = document.getElementById("TxtUserPassword").value; var repassword = document.getElementById("TxtUserPasswordConfirm").value; var identity = document.getElementById("TxtUserIdentity").value; var mobile = document.getElementById("TxtUserMobile").value; var realName = document.getElementById("TxtUserRealName").value; var btnSave = document.getElementById("btnSave"); var identityReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; var mobileReg = /1[3-8]+\d{9}/; if (userName == "" || userName == null) { alert("用户名不能为空"); return false; } else if (password == "" || password == null) { alert("密码不能为空"); return false; } else if (repassword == "" || repassword == null || repassword != password) { alert("对不起,两次输入密码不一样"); return false; } else if (identity == "" || identity == null || identityReg.test(identity) === false) { alert("请输入合法的身份证号码"); return false; } else if (mobile == "" || mobile == null || mobileReg.test(mobile) == false) { alert("请输入合法的手机号码"); return false; } else if (realName == "" || realName == null) { alert("姓名不能为空"); return false; } return true; } |
上面的return ture和false是很重要的,这决定了是否往下执行,往下执行就应该是将数据提交到后台处理数据。当返回true时,后台执行button1_Click这个方法(事件)。
总结
以上是生活随笔为你收集整理的asp.net服务器控件button先执行js再执行后台的方法的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 在JAVA中使用MongoDB
- 下一篇: 让asp.net程序在修改web.con