Uploading file using asynchronous postback in Ajax update panel control is not possible because file manipulation and file uploading is restricted in client side due to security reasons. File upload control inside Ajax update panel control will not work with partial postback because upload control needs to full page post back. File upload control always need to post full postback.Update Panel Triggers are allows us to post full postback and partial postback.
Open Visual Studio 2010 and select File > New Web Site (Shift + Alt +N ) > ASP.NET Web Application.
Open the Default.aspx page and add the following code:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<h2>
File Upload Control within Upload Panel control using asp.net
</h2>
<p>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional">
<Triggers>
<asp:PostBackTrigger ControlID="btUpload" />
</Triggers>
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btUpload" runat="server" Text="Upload" OnClick="btUpload_Click" />
<asp:Label ID="lMsg" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</p>
Open the code behind file and add the following code:
C#
protected void btUpload_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.HasFile)
{
string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Files/" + filename));
lMsg.ForeColor = System.Drawing.Color.Green;
lMsg.Text = "File uploaded successfully.";
}
}
catch (Exception ex)
{
lMsg.ForeColor = System.Drawing.Color.Red;
lMsg.Text = "Error:" + ex.Message.ToString();
}
}
VB.NET
Protected Sub btUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
If FileUpload1.HasFile Then
Dim filename As String = System.IO.Path.GetFileName(FileUpload1.FileName)
FileUpload1.SaveAs(Server.MapPath("~/Files/" + filename))
lMsg.ForeColor = System.Drawing.Color.Green
lMsg.Text = "File uploaded successfully."
End If
Catch ex As Exception
lMsg.ForeColor = System.Drawing.Color.Red
lMsg.Text = "Error:" + ex.Message.ToString()
End Try
End Sub
