asp.net伺服器控制項button先執行js再執行背景方法

來源:互聯網
上載者:User

標籤:http   io   ar   os   使用   sp   java   資料   on   

關於button這個伺服器控制項,我一直想減少它向伺服器提交資料。那些檢測,還是在用戶端實現就好了。
這就需要javascript,但是我發現僅僅有javascript還是不夠的。button伺服器控制項的單擊事件叫“onClick”,
所以javascript就無法使用這個事件。因為重名了。我想實現的是單擊button的時候,先執行用戶端的javascript代碼,然後再執行後台事件。

如果使用的是html控制項,就不存在這種問題了。但是,我就是想實現伺服器控制項的這一功能,有時候伺服器控制項也是很好用的。

先給aspx頁面增加一個伺服器控制項button

 

?
1 </asp:button>


在頁面初始化的時候,給button這個伺服器控制項增加一個用戶端事件。也就是在Page_Load()這個方法裡面加一句代碼:

 

 

?
12345 if (!IsPostBack)            {                //給button1添加用戶端事件                btnSave.Attributes.Add("OnClick", "return UserAddVerify()");            }


UserAddVerify 是js端實現的函數,主要用來檢測資料的有效性。

 

 

?
1234567891011121314151617181920212223242526272829303132333435363738 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再執行背景方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.