FileUpload Control In UpdatePanel Asp.Net Ajax

1:48:00 am 0 Comments

If you are uploading files with FileUpload Control In UpdatePanel Using Asp.Net Ajax and not able to do so, this is because few controls doesn't work with Ajax or Partial page postbacks.

FileUpload1.HasFile method returns false inside Update Panel.

FileUpload HasFile Return False In UpdatePanel

To make full page postback for uploads to work we need to define PostBackTrigger for upload button outside ContentTemplate in html source.

HTML SOURCE
   1:  <asp:ScriptManager ID="ScriptManager1" runat="server"/>
   2:   
   3:  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
   4:  <ContentTemplate>
   5:  <asp:FileUpload ID="FileUpload1" runat="server" />
   6:  <asp:Button ID="btnUpload" runat="server" 
   7:              Text="Upload File" 
   8:              onclick="btnUpload_Click"/>
   9:  <asp:Label ID="lblMessage" runat="server"></asp:Label>
  10:  </ContentTemplate>
  11:   
  12:  <Triggers>
  13:  <asp:PostBackTrigger ControlID="btnUpload" />
  14:  </Triggers>
  15:  </asp:UpdatePanel>

Now we can write code in Click Event of Button to Upload Files With FileUpload Control In UpdatePanel.
1protected void btnUpload_Click(object sender, EventArgs e)
2    {
3        if (FileUpload1.HasFile)
4        {
5            string fileName = FileUpload1.PostedFile.FileName;
6            FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + fileName));
7            lblMessage.Text = "File uploaded successfully";
8        }
9    }

FileUpload Control In UpdatePanel Asp.Net Ajax

0 comments: