In this article I am explaining a common issue faced by many developers. The issue is how to use FileUpload control in ASP.Net UpdatePanel. I think, two Situations you might face when using it with UpdatePanel.
Example:
Situation 1
If the postback is caused by the control which placed inside UpdatePanel, FileUpload is always empty when it has come to the server, regardless whether a file has been selected by user or not.Example:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
</ContentTemplate>
</asp:UpdatePanel>
Solution
Thats because the FileuUpload does not retain the file inside the UpdatePanel.Workaround is to set a PostBackTrigger on the button that updates the UpdatePanel. <asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnSave" />
</Triggers>
</asp:UpdatePanel>
Situation 2
FileUpload does not work if it is loaded not on the initial page load but appears only after asynchronous update of the page part. For example, Panel is invisible at the load time and is shown after clicking on btnShow button. <asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnShow" runat="server" Text="Show" OnClick="btnShow_Click" />
<asp:Panel ID="pnlUpload" runat="server" Visible="False">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnSave" />
</Triggers>
</asp:UpdatePanel>
Solution
Workaround is to add a 'multipart' attribute to your form because during asynchronous postback the form is not updated. That is why it is required to set the form content type explicitly.<form id="form1" runat="server" enctype="multipart/form-data">
OR
// set it on Page_load
Page.Form.Attributes.Add("enctype", "multipart/form-data");
That’s it!!…..Happy Programming...
No comments:
Post a Comment