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/

18 Comments

  • This is what the IPostBackEventHandler interface is for.

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



    -Mike

  • Excellent article. Just what I was looking for. Short sweet and easy to understand. Thank you.

  • Glad it helped.

    -Mahtew Nolton

  • As Mike, I also can't get it to work. The application compiles, but I don't get the event. (I put the onmousedown&quot;javascript:&lt;%#getPostBack()%&gt;;&quot; part in an &lt;area&gt; tag of a &lt;map&gt; , but clicking in the picture that uses the map didn't trigger a postback.

  • The Page_Load requires DataBind(); in order for the &quot;&lt;%#&quot; tag to work

  • 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().

  • thnx a lot! worked for me fine.

  • 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.

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

    Regards,
    Mahi.

  • Would you mind to post a sample source code file ?

  • 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





    ##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));
    }
    }
    }
    }

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

  • Execellent !


    Thanx

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

    onclick=""

  • 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);

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

  • 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

Comments have been disabled for this content.