To use the standard ASP.NET WinForm "__doPostBack(eventTarget, eventArgument)" with standard html controls we have three requirements:
1) insure the "__doPostBack" client side Javascript is embedded
2) configure the client side "onClick" to to call the "__doPostBack" routine
3) intercept the event in the Page_Load on the server
Since we are working with a Web User Control, we do not know if there is any controls requiring the "__doPostBack" code to be included on the page. To insure that the code is included we can kill to birds with one stone and force the "__doPostBack" code to be included and at the same time, configure the onClick on the control we want to use. We use the "Page.GetPostBackClientEvent".
On the server side, we can intercept the event in the Page_Load by checking if it is a post back event and then checking the values of the two hidden form controls "__EVENTTARGET" which is the control that triggered the event and the "__EVENTARGUMENT" where is the argument such as the one we set in the "Page.GetPostBackClientEvent".
Here is an example that only has one DIV, which when clicked, we will intercept and increase a counter:
First, create a web user control called "DivTest". In the "DivTest.ascx" we have:
<DIV id="DivTestControl" runat="server" style="text-align:center">
</DIV>
In the "DivTest.ascx.cs" code behind we have:
namespace DivTest
{
using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
public abstract class Me : System.Web.UI.UserControl
{
protected HtmlGenericControl DivTestControl;
private void Page_Load(object sender, System.EventArgs e)
{
// simple counter to show clicks
int count = 0;
if(ViewState["Count"]==null)
{
ViewState["Count"]=count;
}
else
{
count = Convert.ToInt32(ViewState["Count"]);
}
// Setup client side "onClick" handler
// and insure the "__doPostBack" client code
// gets included on the page.
// The argument "Clicked" is simply a made up name,
// you could use any command or even pass a null and
// not bother with an argument.
DivTestControl.Attributes["onClick"] =
Page.GetPostBackClientEvent(DivTestControl,"Clicked");
// Make sure we are in a post back state
if(IsPostBack)
{
// Check if the event was generated from
// our control by looking at the "__EVENTTARGET".
// We compare against the ".UniqueID" of the
// control so we have the name as it will
// appear on the actual page which is the one
// that will be sent back.
if(DivTestControl.UniqueID.Equals(
Request.Form["__EVENTTARGET"]))
{
// Was our control, so lets see what command.
// We could use several if needed and pick the
// ones to which we will respond.
if(Request.Form["__EVENTARGUMENT"]=="Clicked")
{
// Hey we made it, even was fired, so do something
count++;
ViewState["Count"]=count;
}
}
}
// Display our counter
DivTestControl.InnerHtml="Counter: "+count.ToString();
}
}
}