I recently had a tricky situation where I needed to execute some JavaScript code before performing a post back and everything had to be done via a button. After a bit of research I decided that the button itself shouldn’t perform the postback, so I instead replaced it with an HTML <button> element who’s onclick event was executing my JavaScript function. All good so far on the client side. Shifting over to the client side, I used Page.ClientScript.GetPostBackEventReference which returned me some JavaScript code that can initiate a post back for a given control and a specific argument. The messy part was that I had to somehow inject that call into my JavaScript function so I decided to create the function on the server and register it via Page.ClientScript.RegisterStartupScript:

string postBackRef = Page.ClientScript.GetPostBackEventReference(new PostBackOptions(this, "gotoGoogle"));
  if (!Page.ClientScript.IsStartupScriptRegistered("jsRedirect"))
  {
   Page.ClientScript.RegisterStartupScript(this.GetType(),"jsRedirect","function Redirect(){nt alert(‘hello’);nt"+postBackRef +"n;}",true);
  }

So in this example, the function Redirect is registered which alerts the user with the message "hello" and performs a post back with an event argument "gotoGoogle".

It is now time to "listen" to this post back. During the load event of the page life cycle, we simply check if the current call is a post back and then check if the event argument is the one we specified earlier(gotoGoogle):

if (Page.IsPostBack)
  {
   if(!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]))
   {
    string eventArgument = Request["__EVENTARGUMENT"];
    if (string.Compare(eventArgument, "gotoGoogle", StringComparison.OrdinalIgnoreCase) == 0)
    {
     Response.Redirect("http://www.google.com");
    }
   }
  }

Advertisements