Click ASP.NET button from jQuery dialog button eve

2019-07-24 03:08发布

问题:

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:

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.



回答2:

$("#<%=btnSave.ClientID %>").click();