Friday 4 October 2013

Why fileupload control does not work inside update panel. How I will get out from this problem.

In this article, I have explained why fileupload control does not work inside update panel. How I will get the solution for this.

The fileupload control does not work for uploading image using Asynchronous postback when placed inside update panel. Because fileupload control required full postback control to get the image.If you check fileupload1.hashfile method or filename property ,it shows null value , because update does not retain the file inside the file control.

Solution for working fileupload control inside update panel:-
To solve this problem we have to use trigger inside update panel.We have to set PostBackTrigger intead of Asynchronous inside trigger for button control. By doing this the upload button button will full post back and get and retain the image in fileupload control whenever you clicked on.
So do like as below.

Now Take an example:-

Design a page like or take one fileupload control , one button and image control on page.

<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" />
            <asp:Image ID="Image1" runat="server" Width="200px" />
        </ContentTemplate>
        <Triggers>
        <asp:PostBackTrigger ControlID="Button1"></asp:PostBackTrigger>
        </Triggers>
        </asp:UpdatePanel>


Code for Button click event:-

protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string imgPath = Server.MapPath("~/Images/" + Guid.NewGuid() + FileUpload1.FileName);
            FileUpload1.SaveAs(imgPath);
            string showImagePath=imgPath.Substring(imgPath.LastIndexOf("\\"));
            Image1.ImageUrl = "~/Images" + showImagePath;
        }
    }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.