Asp – Upload fails once, then works correctly

ajaxasp.netfile uploadnetupdatepanel

I'm working on an ASP.Net custom control. In my control I have a FileUpload control, inside a MultiView, inside an AJAX UpdatePanel.

I've added the submit button to the post back triggers of the update panel. (This is the standard fix for getting a FileUpload to work within an UpdatePanel).

On the first submit the FileUpload does not upload anything (ie, the control's FileBytes property has zero length). Everything else on the form submits properly.

On the second and subsequent submits, the upload works correctly.

What could cause this, and how do I fix it?


For example:

<asp:UpdatePanel runat="server" ID="update_panel" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:MultiView runat="server" ID="mvMultiView" ActiveViewIndex="0">
            <asp:View runat="server" ID="viewOne">
                <!-- content -->
            </asp:View>
            <asp:View runat="server" ID="viewTwo">
                <!-- some other form elements -->
                <asp:FileUpload ID="file_upload" runat="server" />
                <asp:Button ID="save_button" runat="server" Text="Save" OnClick="save_Click" ValidationGroup="group" />
            </asp:View>
         </asp:MultiView>
    </ContentTemplate>
    <Triggers>
        <asp:PostBackTrigger ControlID="save_button" />
    </Triggers>
</ajax:UpdatePanel>

Best Answer

This turned out to be caused by the FileUpload Control being rendered during a partial page update. To submit properly the FileUpload control needs to be rendered and submitted using full post backs. Because the first form submit caused a full post back, the upload began working as intended the second time around.

Solution: Add both of the buttons that display and submit the file upload control to the update panels post back triggers.

eg:

   <Triggers>
      <asp:PostBackTrigger ControlID="btnShowUploadForm" />
      <asp:PostBackTrigger ControlID="btnUpload" />
   </Triggers>