views:

63

answers:

2

I have the following ASP.NET markup:

<div id="myForm" title="My Form" style="display: none">
    <span>You can see me!</span>
    <div style="display: none">
        <asp:Button ID="btnSave" runat="server" Text="Button"
            OnClick="btnSave_Click" />
    </div>
</div>

<!-- called by an element click event elsewhere -->
<script type="text/javascript" language="javascript">
    $("#myForm").dialog({
        modal: true,
        width: 500,
        height: 200,
        resizable: false,
        buttons: {
            "Cancel": function () {
                $(this).dialog("close");
            },
            "Save": function () {
                $(this).dialog("close");
                // I want to call btnSave_Click (by DOM-clicking the button?)
            }
        }
    });
    $("#myForm").parent().appendTo("form:first");
</script>

I'm trying to get the jQuery.dialog generated buttons to perform the postback in place of the ASP.NET button. What should I do to make the button do a submit and call the btnSave_Click method?


EDIT

"Save": function () {
    $(this).dialog("close");
    document.getElementById("<%=btnSave.ClientID %>").click();
}

... works but is this the best solution?

+1  A: 

You can use the btnSave.ClientId property to emit to the javascript the ID of the control you are looking for, then you can do something like this. This is if you want the btnSave control to register as a postback control, triggering the "Click" event in the code behind.

var myControl = document.getElementById('theclientidgoeshere')
myControl.click();

That will do it!

If you want to do a simple postback you can do

this.document.form.submit();

but that will NOT register any events for the button.

Is This Best?

For .NET 3.5 and earlier it is the only "truly" safe ways to get the client ID. With jQuery you could do a partial id match on _btnSave, but I find that that is too risky for future modifications.

.NET 4.0 does introduce an option that might help.

.NET 4.0 ClientIDMode Property

In .NET 4.0 you have an optional ClientIDMode Property that will allow you to choose how the client id is created. You can use Predictable or Static options to allow you to hard-code the id of the button into your JavaScript.

Mitchel Sellers
I just updated my question with this solution :) But it doesn't look great to me. Is this the best way?
Codesleuth
For .NET 3.5 and earlier yes, it is the best, and ONLY solution. I'll update my post with a .NET 4.0 alternative
Mitchel Sellers
Ok, it has been updated
Mitchel Sellers
+1  A: 
$("#<%=btnSave.ClientID %>").click();
Tion