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.
- <Triggers>
-
- <asp:PostBackTrigger ControlID="btnUpload" />
-
- </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.
- <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxtoolkit" %>
Copy the following code inside .aspx body section.
- <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>
-
- <asp:UpdatePanel ID="up1" runat="server">
-
- <Triggers>
-
- <asp:PostBackTrigger ControlID="btnUpload" />
-
- </Triggers>
-
- <ContentTemplate>
-
- <asp:FileUpload ID="fuImgPath" runat="server" />
-
- <asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
-
- <br />
-
- <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
-
- </ContentTemplate>
-
- </asp:UpdatePanel>
CodeBehind :
- protected void btnUpload_Click(object sender, EventArgs e)
- {
-
- string strFilePath = string.Empty;
-
- if (fuImgPath.HasFile)
- {
-
- string extension = System.IO.Path.GetExtension(fuImgPath.FileName);
-
- if (extension.ToUpper() != ".JPG" && extension.ToUpper() != ".GIF" && extension.ToUpper() != ".PNG" && extension.ToUpper() != ".JPEG" && extension.ToUpper() != ".BMP")
-
- {
-
- lblMsg.Text = "Upload JPG/PNG/JPEG images only.";
-
- lblMsg.ForeColor = System.Drawing.Color.Red;
-
- return;
-
- }
-
- strFilePath = DateTime.Now.ToString("yyyyMMddHHmmss") + fuImgPath.PostedFile.FileName;
-
- fuImgPath.PostedFile.SaveAs(Server.MapPath(@"~/Application/FileUploads/" + strFilePath.Trim()));
-
- strFilePath = @"~/Application/Masters/FileUploads/Employee/" + strFilePath.Trim();
-
- }
-
- }
I hope you enjoyed it. Please provide your valuable suggestions and feedback.