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
- 下一篇: 《HTML5 界面设计与开发》 读书笔记