Add server control to my custom webcontrol that fires javascript function and a server side function

738 Views Asked by At

In ASP.Net, I am trying to create a WebControl. In this control, I have RenderControl method overridden with my html controls.

protected override void RenderContents(HtmlTextWriter output)
{
    output.Write(@"<table><tr><td>");
    output.Write(@"<input type=""submit"" name=""btnExecute"" value=""Execute""  id=""btnExecute"" />");
    output.Write(@"</td></tr></table>");
}

How can I make the button call the click event so that the server side method btnExecute_Click() can be called? Also, this button calls a javascript function before server side even.

Please suggest how to make it work.

1

There are 1 best solutions below

0
On

Check out this example on how to implement a CompositeControl (which is derivative of WebControl).

http://msdn.microsoft.com/en-us/library/3257x3ea.aspx#Y114

Your button there will exist as a private member of your Composite. You'll initialize it and wire it to a server-side method in CreateChildControls. Then you'll call your button's RenderControl method when you override the Render method of your CompositeControl. Doing it this way will make the button emit the javascript which wires up the click event to an asp.net postback.

As for JS that runs before the callback... well, that could be a little tricky. My suggestion would be to just give the Button a unique CSS Class and wire up your method with jQuery. However, I'm not sure how you would delay the ASP.Net postback until your client method is done... To me this feels like a pattern bastardization, it seems like you would either want to do all of this server side (traditional Asp.Net controls with postbacks) or do it all client side (jquery with ajax).