Monday, July 13, 2009

Fileupload control not working with in updatepanel

I have found the problem, while accessing the fileupload control with in update panel. selected file path get cleared when postback.. i have found one solution for that problem. let me explain the solution with example.

i have used one asp hidden control, using javascript before postback am assigning the path in to hidden control. while accessing server side am getting the path from hidden contrl.

Let's go through the sample.

Aspx Code

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
</asp:ScriptManager>
<asp:UpdatePanel ID="upDate" runat="server">
<ContentTemplate>
<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Button ID="btnSave" runat="server" onclick="btnSave_Click" />
<asp:HiddenField ID="hidFileName" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>

Javascript:

function fileUploads(objGetId, objHidId) {
var objfile = document.getElementById(objGetId);
var objhid = document.getElementById(objHidId);
if (objfile != null) {
objhid.value = objfile.value;
}
}

C# Code

protected void Page_Load(object sender, EventArgs e)
{

btnSave.Attributes.Add("onclick", "javascript:fileUploads('fileUpload','"+hidFileName.ClientID+"')");
// string test = fileUpload.FileName;

}

protected void btnSave_Click(object sender, EventArgs e)
{
string test = hidFileName.Value;
}