File uploads not working within jQuery UI Dialog

2019-06-28 09:06发布

问题:

So I have a rather odd issue that I wanted to see if anyone has some insight into.

I have a page in which I display a grid of files that have been uploaded to our server. The toolbar for the grid provides them with the ability to upload more files. When they click the "Add File" button on the toolbar, a jQuery UI Dialog modal window appears with a simple file upload control in it. After they select a file, they click the "Upload" button on the Dialog which submits the underlying form for uploading. Also note that because I'm using asp.net, there is only one form on the page so I'm not submitting the wrong form.

Now... when I attempt to look for uploaded files on the backend, no files are uploaded. What's worse, if I move the upload control out of the dialog div and use it straight from the page without a dialog, the uploads work fine.

This leads me to believe that even though I am defining the div that will become my dialog within the main form to allow it to submit with a postback, jQuery is somehow moving it or disassociating it from the form.

Is this possible? Or is there something else I may be missing? I can't seem to find any documentation that says either way. Thanks in advance!

回答1:

You're right. Dialog moves its content outside of its form, and appends it to body. Probably to gain better control of the DOM, to make sure it always displays in the center, above everything else, and is not contained in some absolutely positioned DIV or so...



回答2:

You need to move the dialog to inside the form.

var dialog = $("#dialog").dialog({
  autoOpen: false,
  height: 300,
  width: 350,
  modal: true,
  buttons: {
    "Upload": function() {
      __doPostBack('uploadfile', '');
      $( this ).dialog( "close" );
    },
    Cancel: function() {
      $(this).dialog("close");
    }
  }
});

dialog.parent().appendTo($("form:first"));



回答3:

What is occurring here is that the Block UI removes all click functionality on buttons within its modal. To get around this the best solution I have found is to have a hidden button which will then do the desired processing.

Here is an example:

HTML

<asp:Button runat="server" ID="btn_Upload" OnClientClick="UploadFiles(); return false;" />
<asp:Button runat="server" ID="btn_UploadClick" OnClick="btn_UploadFiles_Click" style="display:none;" />

Javascript/Jquery

function UploadFiles()
{
    $.unblockUI({
        onUnblock: function() {
            $('[id$=btn_UploadClick]').click();
        }
     });
}