Creating a Custom ASP.NET Control with Postback OnClick Event
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:
- ClientScriptManager.GetPostBackClientHyperlink()
- ClientScriptManager.GetPostBackEventReference()
The ClientScriptManager is available as an instance property of the Page class, including Control.Page as Page.ClientScript.
ClientScriptManager.GetPostBackClientHyperlink()
This method returns javascript:__doPostBack() as a string. It is suitable for using in an anchor href or onclick event handler. Unfortunately it prepends the javascript: to the front of the string, which is kind of ugly, but also makes it hard to use if you wanted to do a more complicated function. Because I wanted to be able to call client-side scripts before doing the post-back it was unusable for me.
ClientScriptManager.GetPostBackEventReference()
This method takes several parameters, including the names of an EventArgument, a ValidationGroup, and other goodies like tracking control focus between postbacks. The method returned is WebForm_DoPostBackWithOptions(), and also does not include the javascript: that GetPostBackClientHyperLink() gives you.
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)
{
switch (eventArgument)
{
case EVENTARGUMENT_CLICK:
this.FireOnClick();
break;
default:
break;
}
}
The FireOnClick() method fires the Click EventHandler.
Conclusion
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.