Mathew Nolton Blog

Software dementia unleashed...

Forcing a Postback using ASP.Net and JavaScript

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.

protected void Page_Load(object sender, System.EventArgs e)

{

       // this Is a postback, then we care

       if( this.IsPostBack )

       {

              // determine who caused the post back

              string eventArg = Request[ "__EVENTARGUMENT" ];

              // if null ( could it ever be null? )

              if( eventArg != null )

              {

                     // this post back can occur if we raise the event or if the Web Form itself raises the event.

                     // therefore, i always like to put something in the eventarg that lets me identify it as an event

                     // that i raised. i use @@@@@. but you can use whatever you like, just make sure it is unique. 

 

                     // i also like to make the ClientId part of the value if i am posting back within a user control or

                     // custom control. including the ClientId in a user or custom control enables me to programmatically

                     // determine which instance of the control executed the postback. again we do this because all postbacks

                     // for all instances of all controls on the page are being funneled through this one method.

                     int offset = eventArg.IndexOf( "@@@@@" );

                     if( offset > -1 )

                     {

                          // this is an event that we raised. so do whatever you need to here.

                     }

              }

       }

}

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

Mathew



--
Composed with Newz Crawler 1.4 http://www.newzcrawler.com/

Comments

Jesse Ezell said:

This is what the IPostBackEventHandler interface is for.
# June 4, 2003 4:20 PM

Mike said:

Hey... Can you show the whole thing? This isn't appearing for me in IE at least..

-Mike
# September 3, 2003 1:40 PM

Steve Owens said:

Excellent article. Just what I was looking for. Short sweet and easy to understand. Thank you.
# February 25, 2004 11:07 AM

Mathew Nolton said:

Glad it helped.
-Mahtew Nolton
# February 25, 2004 11:41 AM

Kurt said:

As Mike, I also can't get it to work. The application compiles, but I don't get the event. (I put the onmousedown"javascript:<%#getPostBack()%>;" part in an <area> tag of a <map> , but clicking in the picture that uses the map didn't trigger a postback.
# April 3, 2004 9:48 AM

Nick Lucas said:

The Page_Load requires DataBind(); in order for the "<%#" tag to work
# May 12, 2004 9:42 AM

JefferMC@nos~pam.hotmail.com said:

This note was incredibly useful, and even the first reply was helpful and got me looking around on the MSDN site.

I combined your technique for calling server-side code to generate the postback reference. Then I inherited tbe IPostbackEventHandler interface into my user control and used RaisePostBackEvent() and a custom event argument class containing the string passed to GetPostback() to create an OnClick() event with a useful argument. Having an OnClick() event was much cleaner to me than having to test in OnLoad().
# May 25, 2004 10:16 AM

Victoria said:

thnx a lot! worked for me fine.
# June 17, 2004 9:06 PM

swarna said:

hi,
i've one doubt.If i click one radio button two text boxes should be visible and i gave them inside div tag.its working fine.If i submit the form it gets submitted,the problem is if i click on the back button the textbox value is retained but its not visible.how to do this?

regards,
swarna
# June 28, 2004 10:53 AM

Paul Ruiz Pauker said:

Hi, very good article!!!

I want to do the same, but with Framework 1, but this function is new on Framework 2.0, any idea on how to do it? what function should I use?

thanks in advance,

Paul.

# July 17, 2007 3:56 AM

Mahendra said:

Hi. Thanks for the article. A very useful technique in a simple way to implement.

Very Good one.

Regards,

Mahi.

# July 30, 2007 4:32 PM

James said:

Would you mind to post a sample source code file ?

# October 28, 2007 9:29 PM

Lance said:

Thanks matt!  I just used this with the ASP.NET menu control.  Normally the menuItems just take a URL as place to navigate to, I couldn't get them to postback until I did your magic:

##the menu control is dynamically populated in the codebehind

<asp:menu id="menu_catalogue"

   disappearafter="500"

   staticdisplaylevels="2"

   statici

   orientation="Vertical"

   CssSelectorClass="CatalogueMenu"

   runat="server" >

</asp:menu>

##here's where the products are added in the recursive heirarchy loop

...

MenuItem miProduct = new MenuItem();

miProduct.Text = string.Format("{0}", p.shortDescription);

string args = string.Format("@@@@@{0}|{1}",

 Strings.EncodeStringForURI(p.productCode),

 Strings.EncodeStringForURI(p.shortDescription));

string javascript = ClientScript.GetPostBackEventReference(menu_catalogue, args);

string link =  string.Format("javascript:{0}",javascript);

               miProduct.NavigateUrl = link;

...

## and now the code that looks for the postback:

protected void Page_Load(object sender, EventArgs e)

{

   CheckForMenuItemProductClick();

...

private void CheckForMenuItemProductClick()

{

 if (this.IsPostBack)

 {

   string eventArg = Request["__EVENTARGUMENT"];

   if (eventArg != null)

   {

      int offset = eventArg.IndexOf("@@@@@");

      if (offset > -1)

      {

        string args = eventArg.Substring(5); //get rid of the @@@@@

        SaveSessionInfo();

        CallConfig(Strings.DecodeURIString(args));

                   }

               }

           }

       }

# March 20, 2008 9:42 AM

Mike V said:

I found that you must let the Page load code fire during each IsPostBack or the TextChanged event only fires once. .Net 1.1

# April 22, 2008 12:43 PM

Michael said:

Execellent !

Thanx

# August 20, 2008 8:52 AM

Chris Erickson said:

I found using this on dotnet 3.5, it is easiest to do it like this:

onclick="<%= ClientScript.GetPostBackEventReference(this, "@@@@@buttonPostBack") %>"

# December 17, 2008 10:54 AM

tillito said:

This is not exactly the topic but I was looking for this for a while.

If you want to initiate a post-back from the code-behind, simply do:

this.Page_Load(this, null);

# January 19, 2009 11:51 AM

tillito said:

Please forget, what I just wrote... it does not work the way I thought...

# January 19, 2009 11:58 AM

Kunni said:

Hi,

I want to request a webpage in button click and want to dispaly response in UI. Then based on the response status I want to request the webpage again. I want to do it by using postback...is it possible.

can any one help me on this..Thanks in advance..

Kunni

# April 20, 2009 8:53 AM