Note: I’ve been meaning to post this article since September but it is getting too complicated. I’ll include some more info in a future article. Maybe I’ll even make this a series on making custom controls that postback.
I recently had to create a new ASP.NET control that contained a couple of images and a link. Sometimes I wanted it to postback when clicked, and sometimes I wanted it to run a script, and sometimes I wanted it to run a script and then postback. Sounds funny, but it is true. This was a toolbar button control I wanted to create and make it look like one of those Outlook buttons.
I’ll spare you most of the details in what I did, but in the end the way I designed the control I wanted to put an onclick event onto a span that wrapped the other parts of the control (images and text controls). There are two important methods for getting a postback:
The ClientScriptManager is available as an instance property of the Page class, including Control.Page as Page.ClientScript.
To make GetPostBackEventReference() work your control must implement the IPostBackEventHandler (and that is easy). Use IPostBackEventHandler.RaisePostBackEvent(string eventArgument) and switch on the eventArgument to define the server-side behaviour. For example, I passed “clicked” as the eventArgument to GetPostBackEventReference() so my RaisePostBackEvent() looks something like this:
void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
The FireOnClick() method fires the Click EventHandler.
Its easy to get the Client-Script to Postback using the GetPostBackEventReference() method.
In my next article I’ll describe how to execute your own Client-Side OnClick event before posting back to the server.