asp.net服务器控件button先执行js再执行后台的方法
關(guān)于button這個(gè)服務(wù)器控件,我一直想減少它向服務(wù)器提交數(shù)據(jù)。那些檢測,還是在客戶端實(shí)現(xiàn)就好了。
這就需要javascript,但是我發(fā)現(xiàn)僅僅有javascript還是不夠的。button服務(wù)器控件的單擊事件叫“onClick”,
所以javascript就無法使用這個(gè)事件。因?yàn)橹孛恕N蚁雽?shí)現(xiàn)的是單擊button的時(shí)候,先執(zhí)行客戶端的javascript代碼,然后再執(zhí)行后臺(tái)事件。
如果使用的是html控件,就不存在這種問題了。但是,我就是想實(shí)現(xiàn)服務(wù)器控件的這一功能,有時(shí)候服務(wù)器控件也是很好用的。
先給aspx頁面增加一個(gè)服務(wù)器控件button
?
?| 1 | </asp:button> |
在頁面初始化的時(shí)候,給button這個(gè)服務(wù)器控件增加一個(gè)客戶端事件。也就是在Page_Load()這個(gè)方法里面加一句代碼:
?
?
?| 1 2 3 4 5 | if (!IsPostBack) ????????????{ ????????????????//給button1添加客戶端事件 ????????????????btnSave.Attributes.Add("OnClick", "return UserAddVerify()"); ????????????} |
UserAddVerify 是js端實(shí)現(xiàn)的函數(shù),主要用來檢測數(shù)據(jù)的有效性。
?
?
?| 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("請輸入合法的手機(jī)號碼"); ????????return false; ????} ????else if (realName == "" || realName == null) { ????????alert("姓名不能為空"); ????????return false; ????} ????return true; } |
上面的return ture和false是很重要的,這決定了是否往下執(zhí)行,往下執(zhí)行就應(yīng)該是將數(shù)據(jù)提交到后臺(tái)處理數(shù)據(jù)。當(dāng)返回true時(shí),后臺(tái)執(zhí)行button1_Click這個(gè)方法(事件)。
總結(jié)
以上是生活随笔為你收集整理的asp.net服务器控件button先执行js再执行后台的方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在JAVA中使用MongoDB
- 下一篇: 让asp.net程序在修改web.con