0

In my ASP.NET Web forms application, I am adding a feature to upload files but I don't want to do a full postback. So to make it asynchronous I thought of using UpdatePanel. This UpdatePanel contains a FileUpload control and a button to upload the selected photo. When I was debuggin my code to detect if file is actually selected or not, I found FileUpload's HasFile property to be false.

It works when I remove UpdatePanel but I don't understand why.

To help you understand, here is the code:

ASPX markups:

<asp:UpdatePanel ID="UPProf" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FUDP" runat="server" />
<asp:Button ID="BUDP" runat="server" OnClick="BUDP_Click" Text="Upload your photo" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="BUDP" EventName="Click" />
</Triggers>
</asp:UpdatePanel>

Here's its CS code:

protected void BUDP_Click(object sender, EventArgs e)
{
    try
    {
        if (FUDP.HasFile)  //  code doesn't pass this if condition
        {
            FUDP.SaveAs("D:/Pictures/" + count + ".jpeg");  //it doesn't work since there is no file here
        }
        else
        {
           //Set some message for user
        }
    }
    catch (Exception ex)
    {
        //log the error
    }
}
Akshay Raut
  • 413
  • 5
  • 19

1 Answers1

1

Upload requires full page request. This is a limitation of the XmlHttpRequest component used in all AJAX frameworks for asynchronous calls to the application.

Remove the UpdatePanel or make BUDP button to perform postbacks.

<asp:UpdatePanel ID="UPProf" runat="server">
   <ContentTemplate>
      <asp:FileUpload ID="FUDP" runat="server" />
      <asp:Button ID="BUDP" runat="server" OnClick="BUDP_Click" 
          Text="Upload your photo" />
   </ContentTemplate>
   <Triggers>
      <asp:PostBackTrigger ControlID="BUDP" />
   </Triggers>
</asp:UpdatePanel>
Win
  • 61,100
  • 13
  • 102
  • 181
  • Oh the perils of UpdatePanel! – beautifulcoder Oct 10 '14 at 17:01
  • that refreshes the page, it worked. Thanks. I didn't want it to refresh though. Any other suggestion? Thanks again. – Akshay Raut Oct 10 '14 at 17:09
  • @AKshayRaut There are a lot of third party components for that. You can try [AsyncFileUpload](http://ajaxtoolkit.net/AsyncFileUpload/AsyncFileUpload.aspx). I use [telerik](http://demos.telerik.com/aspnet-ajax/imageeditor/examples/imageupload/defaultcs.aspx?product=asyncupload) – Win Oct 10 '14 at 18:01
  • can you please post a sample code and markup for Ajax and/or Async file upload? – Akshay Raut Oct 15 '14 at 15:04