I found myself wanting to do this and I reviewed the above answers and did a hybrid approach of them. It got a little tricky, but here is what I did:
My button already worked with a server side post. I wanted to let that to continue to work so I left the "OnClick" the same, but added a OnClientClick:
OnClientClick="if (!OnClick_Submit()) return false;"
Here is my full button element in case it matters:
<asp:Button UseSubmitBehavior="false" runat="server" Class="ms-ButtonHeightWidth jiveSiteSettingsSubmit" OnClientClick="if (!OnClick_Submit()) return false;" OnClick="BtnSave_Click" Text="<%$Resources:wss,multipages_okbutton_text%>" id="BtnOK" accesskey="<%$Resources:wss,okbutton_accesskey%>" Enabled="true"/>
If I inspect the onclick attribute of the HTML button at runtime it actually looks like this:
if (!OnClick_Submit()) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$PlaceHolderMain$ctl03$RptControls$BtnOK", "", true, "", "", false, true))
Then in my Javascript I added the OnClick_Submit method. In my case I needed to do a check to see if I needed to show a dialog to the user. If I show the dialog I return false causing the event to stop processing. If I don't show the dialog I return true causing the event to continue processing and my postback logic to run as it used to.
function OnClick_Submit() {
var initiallyActive = initialState.socialized && initialState.activityEnabled;
var socialized = IsSocialized();
var enabled = ActivityStreamsEnabled();
var displayDialog;
// Omitted the setting of displayDialog for clarity
if (displayDialog) {
$("#myDialog").dialog('open');
return false;
}
else {
return true;
}
}
Then in my Javascript code that runs when the dialog is accepted, I do the following depending on how the user interacted with the dialog:
$("#myDialog").dialog('close');
__doPostBack('message', '');
The "message" above is actually different based on what message I want to send.
Back in my server-side code, I changed OnLoad from:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e)
if (IsPostBack)
{
return;
}
// OnLoad logic removed for clarity
}
To:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e)
if (IsPostBack)
{
switch (Request.Form["__EVENTTARGET"])
{
case "message1":
// We did a __doPostBack with the "message1" command provided
Page.Validate();
BtnSave_Click(this, new CommandEventArgs("message1", null));
break;
case "message2":
// We did a __doPostBack with the "message2" command provided
Page.Validate();
BtnSave_Click(this, new CommandEventArgs("message2", null));
break;
}
return;
}
// OnLoad logic removed for clarity
}
Then in BtnSave_Click method I do the following:
CommandEventArgs commandEventArgs = e as CommandEventArgs;
string message = (commandEventArgs == null) ? null : commandEventArgs.CommandName;
And finally I can provide logic based on whether or not I have a message and based on the value of that message.