File Upload Control is not working in Update Panel

In this blog you will learn a common issue faced by many new developers. The issue is simple that is the FileUpload control in ASP.Net AJAX UpdatePanel is does not contain any files and also the HasFile property is false when the file is uploaded.

The answer is by just changing the Trigger of the upload button from AsyncPostBackTrigger to PostBackTrigger. This means that even if the FileUpload control is inside UpdatePanel still there will be a Full Postback when upload button is clicked.

  1. <Triggers>  
  2.   
  3.    <asp:PostBackTrigger ControlID="btnUpload" />  
  4.   
  5. </Triggers>  

Lets take an example:

First Create a new "Empty ASP.NET Web Application".

Add reference (ajaxcontroltoolkit.dll) to your project.

Add webform to your project.

Next write following line in your .aspx page.

  1. <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxtoolkit" %>  

 

Copy the following code inside .aspx body section.

  1. <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>  
  2.   
  3. <asp:UpdatePanel ID="up1" runat="server">  
  4.   
  5. <Triggers>  
  6.   
  7.          <asp:PostBackTrigger ControlID="btnUpload" />  
  8.   
  9. </Triggers>  
  10.   
  11. <ContentTemplate>  
  12.   
  13.    <asp:FileUpload ID="fuImgPath" runat="server" />  
  14.   
  15.       <asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />  
  16.   
  17. <br />  
  18.   
  19.       <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>  
  20.   
  21.    </ContentTemplate>  
  22.   
  23. </asp:UpdatePanel>  

CodeBehind :

  1. protected void btnUpload_Click(object sender, EventArgs e)   
  2. {  
  3.   
  4.    string strFilePath = string.Empty;  
  5.   
  6.    if (fuImgPath.HasFile)    
  7.    {  
  8.   
  9.       string extension = System.IO.Path.GetExtension(fuImgPath.FileName);  
  10.   
  11.       if (extension.ToUpper() != ".JPG" && extension.ToUpper() != ".GIF" && extension.ToUpper() != ".PNG" && extension.ToUpper() != ".JPEG" && extension.ToUpper() != ".BMP")  
  12.   
  13.       {  
  14.   
  15.          lblMsg.Text = "Upload JPG/PNG/JPEG images only.";  
  16.   
  17.          lblMsg.ForeColor = System.Drawing.Color.Red;  
  18.   
  19.          return;  
  20.   
  21.       }  
  22.   
  23.       strFilePath = DateTime.Now.ToString("yyyyMMddHHmmss") + fuImgPath.PostedFile.FileName;  
  24.   
  25.       fuImgPath.PostedFile.SaveAs(Server.MapPath(@"~/Application/FileUploads/" + strFilePath.Trim()));  
  26.   
  27.       strFilePath = @"~/Application/Masters/FileUploads/Employee/" + strFilePath.Trim();  
  28.   
  29.    }  
  30.   
  31. }  

I hope you enjoyed it. Please provide your valuable suggestions and feedback.

Ebook Download
View all
Learn
View all