Search code examples
c#asp.netpush-back

ASP form losing file attachments on postback


I have an aspx form that contains a series of user inputs and then a submit button that packages that info and sends an email with the parsed data and any attachments.

I'm using an asp:fileupload for the user to attach files to the email, and on the button click it hits a method i wrote in the codebehind that checks to ensure all the required fields were populated, if it's not I kick back an error message popup and focus the first required field that fails. The problem is after the pushback it loses the attachment. So I need to be able to check my fields client side and my background is in C++ so scripting is new to me. Any help is appreciated.

part of my form for visual reference: https://i.sstatic.net/Ioawg.png

showing how I'm doing error handling currently https://i.sstatic.net/PhfQw.png


Solution

  • On postback, the uploadfile will clear; this cannot be prevented. But there are workarounds.

    1. First, if possible, add RequiredValidators to check for missing data on the client side prior to submitting the form.

      <asp:textbox id="Text1" text="Enter a value" runat="server" />
          <asp:requiredfieldvalidator id="RequiredFieldValidator1" controltovalidate="Text1"
              text="Required Field!" runat="server" />
          <asp:button id="Button1" runat="server" text="Validate" />
          <asp:validationsummary id="valSum" displaymode="BulletList" runat="server" headertext="You must enter a value in the following fields:" />
      

    You could also write some javascript to do the auto-focus you are looking for.

    1. If you really need to submit the form and validate it on the codebehind, save the posted file to a temporary folder on the server with a random file name. Update a hidden label or ViewState on the form with the file name so you can get the file back from the server on the next postback. You can hide the upload control and replace it with a label "File {name} ready for upload" and a button "upload different file".

    Note: Do NOT put the actual file contents in viewState or session. That is not going to be good for performance.