asp.net服务器控件button先执行js再执行后台的方法

本文探讨了在ASP.NET页面中如何通过客户端JavaScript实现按钮点击验证,并在验证通过后触发服务器端事件,避免直接提交数据。通过在Page_Load方法中添加客户端事件属性,实现了数据有效性检查与后台处理的分离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于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这个方法(事件)。

转载于:https://www.cnblogs.com/ranran/p/4112141.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值