[c#] jQuery UI Dialog with ASP.NET button postback

I have a jQuery UI Dialog working great on my ASP.NET page:

jQuery(function() {
    jQuery("#dialog").dialog({
        draggable: true,
        resizable: true,
        show: 'Transfer',
        hide: 'Transfer',
        width: 320,
        autoOpen: false,
        minHeight: 10,
        minwidth: 10
    });
});

jQuery(document).ready(function() {
    jQuery("#button_id").click(function(e) {
        jQuery('#dialog').dialog('option', 'position', [e.pageX + 10, e.pageY + 10]);
        jQuery('#dialog').dialog('open');
    });
});

My div:

<div id="dialog" style="text-align: left;display: none;">
    <asp:Button ID="btnButton" runat="server" Text="Button" onclick="btnButton_Click" />
</div>

But the btnButton_Click is never called... How can I solve that?

More information: I added this code to move div to form:

jQuery("#dialog").parent().appendTo(jQuery("form:first"));

But still without success...

This question is related to c# asp.net jquery jquery-ui postback

The answer is


$('#divname').parent().appendTo($("form:first"));

Using this code solved my problem and it worked in every browser, Internet Explorer 7, Firefox 3, and Google Chrome. I start to love jQuery... It's a cool framework.

I have tested with partial render too, exactly what I was looking for. Great!

<script type="text/javascript">
    function openModalDiv(divname) {
        $('#' + divname).dialog({ autoOpen: false, bgiframe: true, modal: true });
        $('#' + divname).dialog('open');
        $('#' + divname).parent().appendTo($("form:first"));
    }

    function closeModalDiv(divname) {
        $('#' + divname).dialog('close');
    }
</script>
...
...
<input id="Button1" type="button" value="Open 1" onclick="javascript:openModalDiv('Div1');" />
...
...
<div id="Div1" title="Basic dialog" >
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
       <ContentTemplate>
          postback test<br />
          <asp:Button ID="but_OK" runat="server" Text="Send request" /><br />
          <asp:TextBox ID="tb_send" runat="server"></asp:TextBox><br />
          <asp:Label ID="lbl_result" runat="server" Text="prova" BackColor="#ff0000></asp:Label>
        </ContentTemplate>
    <asp:UpdatePanel>
    <input id="Button2" type="button" value="cancel" onclick="javascript:closeModalDiv('Div1');" />
</div>

I just added the following line after you created the dialog:

$(".ui-dialog").prependTo("form");

The $('#dialog').parent().appendTo($("form:first")) solution works fine in IE 9. But in IE 8 it makes the dialog appear and disappear directly. You can't see this unless you place some alerts so it seems that the dialog never appears. I spend one morning finding a solution that works on both versions and the only solution that works on both versions 8 and 9 is:

$(".ui-dialog").prependTo("form");

Hope this helps others that are struggeling with the same issue


With ASP.NET just use UseSubmitBehavior="false" in your ASP.NET button:

<asp:Button ID="btnButton" runat="server"  Text="Button" onclick="btnButton_Click" UseSubmitBehavior="false" />       

Reference: Button.UseSubmitBehavior Property


FWIW, the form:first technique didn't work for me.

However, the technique in that blog article did:

http://blog.roonga.com.au/2009/07/using-jquery-ui-dialog-with-aspnet-and.html

Specifically, adding this to the dialog declaration:

  open: function(type,data) {
    $(this).parent().appendTo("form");
  }

This was the clearest solution for me

var dlg2 = $('#dialog2').dialog({
        position: "center",
        autoOpen: false,
        width: 600,
        buttons: {
            "Ok": function() {
                $(this).dialog("close");
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    });

dlg2.parent().appendTo('form:first');
$('#dialog_link2').click(function(){
    dlg2.dialog('open');

All the content inside the dlg2 will be available to insert in your database. Don't forget to change the dialog variable to match yours.


Fantastic! This solved my problem with ASP:Button event not firing inside jQuery modal. Please note, using the jQuery UI modal with the following allows the button event to fire:

// Dialog Link
$('#dialog_link').click(function () {
    $('#dialog').dialog('open');
    $('#dialog').parent().appendTo($("form:first"))
    return false;
});

The following line is the key to get this working!

$('#dialog').parent().appendTo($("form:first"))

Use this line to make this work while using the modal:true option.

open: function (type, data) { 
    $('.ui-widget-overlay').appendTo("form"); $(this).parent().appendTo("form"); 
  },

I didn't want to have to work around this problem for every dialog in my project, so I created a simple jQuery plugin. This plugin is merely for opening new dialogs and placing them within the ASP.NET form:

(function($) {
    /**
     * This is a simple jQuery plugin that works with the jQuery UI
     * dialog. This plugin makes the jQuery UI dialog append to the
     * first form on the page (i.e. the asp.net form) so that
     * forms in the dialog will post back to the server.
     *
     * This plugin is merely used to open dialogs. Use the normal
     * $.fn.dialog() function to close dialogs programatically.
     */
    $.fn.aspdialog = function() {
        if (typeof $.fn.dialog !== "function")
            return;

        var dlg = {};

        if ( (arguments.length == 0)
                || (arguments[0] instanceof String) ) {
            // If we just want to open it without any options
            // we do it this way.
            dlg = this.dialog({ "autoOpen": false });
            dlg.parent().appendTo('form:first');
            dlg.dialog('open');
        }
        else {
            var options = arguments[0];
            options.autoOpen = false;
            options.bgiframe = true;

            dlg = this.dialog(options);
            dlg.parent().appendTo('form:first');
            dlg.dialog('open');
        }
    };
})(jQuery);</code></pre>

So to use the plugin, you first load jQuery UI and then the plugin. Then you can do something like the following:

$('#myDialog1').aspdialog(); // Simple
$('#myDialog2').aspdialog('open'); // The same thing
$('#myDialog3').aspdialog({title: "My Dialog", width: 320, height: 240}); // With options!

To be clear, this plugin assumes you are ready to show the dialog when you call it.


The exact solution is;

$("#dialogDiv").dialog({ other options...,
    open: function (type, data) {
        $(this).parent().appendTo("form");
    }
});

The solution from Robert MacLean with highest number of votes is 99% correct. But the only addition someone might require, as I did, is whenever you need to open up this jQuery dialog, do not forget to append it to parent. Like below:

var dlg = $('#questionPopup').dialog( 'open'); dlg.parent().appendTo($("form:first"));


ken's answer above did the trick for me. The problem with the accepted answer is that it only works if you have a single modal on the page. If you have multiple modals, you'll need to do it inline in the "open" param while initializing the dialog, not after the fact.

open: function(type,data) { $(this).parent().appendTo("form"); }

If you do what the first accepted answer tells you with multiple modals, you'll only get the last modal on the page working firing postbacks properly, not all of them.


Move the dialog the right way, but you should do it only in the button opening the dialog. Here is some additional code in jQuery UI sample:

$('#create-user').click(function() {
    $("#dialog").parent().appendTo($("form:first"))
    $('#dialog').dialog('open');
})

Add your asp:button inside the dialog, and it runs well.

Note: you should change the <button> to <input type=button> to prevent postback after you click the "create user" button.


I know this is an old question, but for anyone who have the same issue there is a newer and simpler solution: an "appendTo" option has been introduced in jQuery UI 1.10.0

http://api.jqueryui.com/dialog/#option-appendTo

$("#dialog").dialog({
    appendTo: "form"
    ....
});

Be aware that there is an additional setting in jQuery UI v1.10. There is an appendTo setting that has been added, to address the ASP.NET workaround you're using to re-add the element to the form.

Try:

$("#dialog").dialog({
     autoOpen: false,
     height: 280,
     width: 440,
     modal: true,
     **appendTo**:"form"
});

Primarily it's because jQuery moves the dialog outside of the form tags using the DOM. Move it back inside the form tags and it should work fine. You can see this by inspecting the element in Firefox.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete

Examples related to postback

Confirm postback OnClientClick button ASP.NET A potentially dangerous Request.Form value was detected from the client Forcing a postback Retrieving data from a POST method in ASP.NET How to use __doPostBack() OnclientClick and OnClick is not working at the same time? ASP.NET postback with JavaScript jQuery UI Dialog with ASP.NET button postback Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'