Search code examples
c#asp.netfile-uploadwebformsupdatepanel

Using FileUpload on a modal popup and handling postbacks


I'm stuck in a catch-22 situation...

I have an ASP.NET 4.0 Webforms application, that uses model popups (using the Ajax Control Toolkit's ModalPopupExtender component) to get inputs from user.

One screen is used to add new members, or edit existing member's records. These records include a picture of the member, which I'm uploading using a standard ASP.NET FileUpload control.

That create/edit screen is wrapped in an UpdatePanel so that when I pop up the overlay, I can fill in the textboxes with existing values (when editing an existing member).

Since the popup uses an UpdatePanel, I had to define an explicit PostBackTrigger so that my Save button will actually cause a complete postback and so that I'm able to read up the bytes of the picture uploaded in the FileUpload control.

<asp:UpdatePanel ID="pnlCreateOrEdit" runat="server">
    <ContentTemplate>
        .... asp.net controls here, including:
        <asp:FileUpload ID="uploadPic" runat="server" />
        ....
        <asp:Button ID="btnSave" runat="server" OnClick="BtnSaveClicked" Text="Save" />
    </ContentTemplate>
    <Triggers>
        <asp:PostBackTrigger ControlID="btnSave"/>
    </Triggers>
</asp:UpdatePanel>

If I don't define that PostBackTrigger, then my uploaded file can't be read out.

BUT: once I define that postback trigger, now I cannot do my validation anymore, since if I do my validation in the btnSaveClicked method and it fails (something is missing for instance), I can detect that - but I can't respond to it anymore, since the popup will be closed no matter what I've tried so far....

protected void BtnSaveClick(object sender, EventArgs e) {
   // do my validation - if something is amiss, don't go any further
   if (!IsValid()) {
      return;
   }

   // read back the data
   // hide the modal popup form
   // call an event handler to process the inputs
}

So now I'm stuck:

  • if I omit the post back trigger, my validation works nicely - if something is wrong, it's flagged and shown on the popup form, and the popup isn't closed
    ==> BUT in that case I cannot read out the bytes of the uploaded picture..... (uploadPic.HasFile is always false)

  • if I put in the post back trigger, my file upload works nicely, I can read out my bytes no problem
    ==> BUT now, my validation - while detecting something's amiss - cannot show the error since the popup form is being closed by the full postback....

Is there any way to get BOTH - the bytes in the FileUpload control, AND the popup staying open if validation fails?


Solution

  • I ended up using the AsyncFileUpload component from the Ajax Control Toolkit - this works nicely on an UpdatePanel and satisfies all my needs.