Postback from javascript – the right way

January 31st, 2008

Sometimes a programmer must do very weird things in his ASP.NET webapp. Among them, there is a postback initiated in custom javascript. Before .NET Framework 2.0, it was no good solution to achieve it. Fortunately it can be done without much effort nowadays.

There is an interface called IPostBackEventHandler which must be implemented by a page or a control. Then you must create javascript containing reference to postback function retrieved by ClientScriptManager.GetPostBackEventReference(...) method.

The sample web control's codebehind can look like below:

C#:
  1. public class MyControl : Control, IPostBackEventHandler
  2. {
  3.     // this method will be called on postback initiated in javascript
  4.     public void RaisePostBackEvent(string eventArgument)
  5.     {
  6.         if (eventArgument == "foo")
  7.         {
  8.             // do something
  9.         }
  10.     }
  11. }

then we create javascript in aspx / ascx file:

ASP:
  1. <script>
  2. function Test()
  3. {
  4.     <%= Page.ClientScript.GetPostBackEventReference(this, "foo"); %>
  5. }
  6. </script>

Now, when a Test() function is called in a browser, our page will do a nice, clean postback :)

2 Responses to “Postback from javascript – the right way”

  1. Xion says:

    Something’s weird in here. Namely, I don’t see connection between that class and script. How does ASP know that it should call MyControl.RaisePostBackEvent (and not SomeWeirdObject.RaisePostBackEvent)? Maybe ‘this’ in ASP is the answer but I rather suppose it’s a Page object…

  2. SirMike says:

    Everything is ok. The javascript tag is embedded on MyControl.ascx
    GetPostBackEventReference gets “this” as the control reference. If it was aspx (not ascx) the “this” reference would point to the page object.
    I changed a post a little bit to make less confusion.

Leave a Reply

Designed by SirMike © All rights reserved

Valid XHTML 1.0! Valid CSS!

Powered by Rootnode