Click ASP.NET button from jQuery dialog button event

こ雲淡風輕ζ 提交于 2020-01-04 07:50:12

问题


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();


来源:https://stackoverflow.com/questions/3354498/click-asp-net-button-from-jquery-dialog-button-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!