Forcing a Postback using ASP.Net and JavaScript.

作者在撰写关于如何编写独特自定义控件的文章时,需在客户端JavaScript中强制回发。介绍了在aspx代码中添加div标签代码、编写getPostBack代码,利用.net方法调用实现回发,还需修改Page_Load()代码判断回发时机,希望对他人有帮助。

The original author of the artical was Mathew Nolton.

I am in the process of putting together an article for how to write a relatively unique custom control. During its writing, I had to force a post back within some client-side javascript. It is a pretty handy piece of code so I thought I would share it with the world.

First, in my aspx code, I put in this piece of code for a div tag.

onmousedown="javascript:getPostBack()%>;"

Next, I wrote the getPostBack piece of code.

protected string getPostBack()

{

   return this.Page.GetPostBackEventReference(this, "@@@@@buttonPostBack"");

}

The getPostBack() method is taking advantage of the GetPostBackEventReference .net method call that enables you to hijack the same client-side javascript postback code for your own use. The second parameter enables you to create a custom event argument that is unique to your own uses. You will need this event argument later...

Next, we need to modify the Page_Load() code in order to determine when a postback occurred.

1protected void Page_Load(object sender, System.EventArgs e)
2{
3 // this Is a postback, then we care
4 if( this.IsPostBack )
5 {
6  // determine who caused the post back
7  string eventArg = Request[ "__EVENTARGUMENT" ];
8
9  // if null ( could it ever be null? )
10  if( eventArg != null )
11  {
12   // this post back can occur if we raise the event or if the Web Form itself raises the event.
13   // therefore, i always like to put something in the eventarg that lets me identify it as an event
14   // that i raised. i use @@@@@. but you can use whatever you like, just make sure it is unique. 
15
16   // i also like to make the ClientId part of the value if i am posting back within a user control or 
17   // custom control. including the ClientId in a user or custom control enables me to programmatically
18   // determine which instance of the control executed the postback. again we do this because all postbacks
19   // for all instances of all controls on the page are being funneled through this one method.
20
21   int offset = eventArg.IndexOf( "@@@@@" ); 
22   if( offset > -1 )
23   {
24    // this is an event that we raised. so do whatever you need to here.
25   } 
26  }
27 }
28}

Hope this helps someone out in VirtualWorld. As always, comments and feedback are appreciated.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值