Click here to Skip to main content
Click here to Skip to main content

Simple AJAX File Upload

By , 29 Dec 2006
 

Introduction

AJAX is a great thing for ASP.NET developers. It has begun to level the playing field with rich client applications, in terms of user experience and responsiveness. One downside has been that many things that once worked are broken; including the FileUpload control.

The essence of the problem is that the FileUpload control does not work with asynchronous postbacks, and therefore does not work from within an AJAX UpdatePanel. The technique presented in this article allows the FileUpload control to work within an UpdatePanel, by forcing a full postback; however, the rest of the controls can still take advantage of the asynchronous postbacks provided by the UpdatePanel. The example application will be a simple web form containing a DatePicker Control, a Label and a FileUpload. We will see that the FileUpload will function via a full postback, but the DatePicker will retain its AJAX behaviour.

1. Create a New AJAX-enabled Web Project

When Microsoft AJAX is installed, it adds a new template to Visual Studio, ASP.NET AJAX-Enabled Web Site. Create a new one of these:

Create a new AJAX Web Site

2. Create a New Web Form

In this example, I have added an Eclipse Web Solutions ASP.NET DatePicker control, a Label, and a FileUpload control, all within an UpdatePanel:

Eclipse Web Solutions ASP.NET DatePicker

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional">
   <ContentTemplate>
      <ews:DatePicker ID="DatePicker1"
         runat="server" UsingUpdatePanel="True" /><br />
      <asp:Label ID="Label1" runat="server"></asp:Label><br /><br />
      <asp:FileUpload ID="FileUpload1" runat="server" />
      <asp:Button ID="Button1" runat="server"
         Text="Upload" />
   </ContentTemplate>
</asp:UpdatePanel>

Code-behind:

protected void DatePicker1_SelectionChanged(object sender, EventArgs e)
{
    Label1.Text = DatePicker1.DateValue.ToShortDateString();
}

protected void Button1_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        Label1.Text = FileUpload1.FileName;
    }
}

It is at this point that we experience the problem. Run the form, and you will find that the file upload control does not work. Because the file upload control is within an UpdatePanel, the file is not posted to the server.

3. Enable File Upload Full Postback

As mentioned earlier, the trick is to force the file upload control to perform a full postback, and we do this using triggers. Triggers allow the developer to specify what will cause partial and full postbacks. They must be defined within the UpdatePanel but outside of the ContentTemplate. We want to create a trigger that will instruct the button that we are using for the upload to perform a full postback. The updated markup is:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional">
 <Triggers>
  <asp:PostBackTrigger ControlID="Button1" />
 </Triggers>
 <ContentTemplate>
  <ews:DatePicker ID="DatePicker1" runat="server" UsingUpdatePanel="True" 
                  OnSelectionChanged="DatePicker1_SelectionChanged" /><br />
  <asp:Label ID="Label1" runat="server"></asp:Label><br /><br />
  <asp:FileUpload ID="FileUpload1" runat="server" />
  <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
 </ContentTemplate>
</asp:UpdatePanel>

Now, when the form is run, the DatePicker is still working asynchronously, but the file upload is also working, thanks to the PostBackTrigger.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

liammclennan
Web Developer
Australia Australia
Member
Liam McLennan has been developing for the internet since 2001. He is passionate about delivering top quality I.T. solutions that address his customer's needs.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
AnswerRe: So,where is ajax here?memberZinkyu30 Jan '09 - 10:22 
GeneralFile UploadmemberHendrikO17 Jun '08 - 1:12 
QuestionUpdate Panel Propblems.memberHasan Mohiuddin Farooqi18 May '08 - 20:06 
QuestionWhat about a file upload control inside an ASCX user control inside an update panelmemberfrankkirchner1 May '08 - 13:21 
AnswerRe: What about a file upload control inside an ASCX user control inside an update panelmemberliammclennan1 May '08 - 13:41 
GeneralRe: What about a file upload control inside an ASCX user control inside an update panelmemberfrankkirchner1 May '08 - 15:28 
AnswerSolution for using this technique with a user controlmemberkbomb98724 Jun '08 - 4:24 
To assign the postback trigger from within a user control, you can use the code-behind to reference the parent page and make the trigger. Here's how:
 
On your parent page, you have the following code somewhere in the page which includes your scriptmanager, updatepanel, and user control that has a file upload in it:
 
<asp:ScriptManager ID="ScriptManager1" runat="server" />
 
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
 
<MyUserControls:MyControl id="usrMyUploadControl" runat="server" ScriptManagerName="ScriptManager1" />
<!-- Notice that we include a public string variable in your user control
called ScriptManagerName which will hold the tag name of your script manager -->
 
</ContentTemplate>
</asp:UpdatePanel>
 
Now, in your user control, you will have the following code which will search for the ScriptManager in the page's collection of nested controls. Then it will register the postback trigger from within your user control. This is how we can reference the user control's upload button, which in this case is called btnUpload.
 
    public string ScriptManagerName = "";
 
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
 
        if (ScriptManagerName.Length > 0)
        {
            ScriptManager scriptManager = (ScriptManager)SearchControl(Page, ScriptManagerName);
            if (scriptManager != null)
            {
                scriptManager.RegisterPostBackControl(btnUpload);
            }
        }
    }
 
    public Control SearchControl(Control container, string id)
    {
        Control control = container.FindControl(id);
        if (control == null)
        {
            foreach (Control c in container.Controls)
            {
                if (c.HasControls())
                {
                    control = SearchControl(c, id);
                    if (control != null) break;
                }
            }
        }
        return control;
    }

GeneralRe: Solution for using this technique with a user controlmemberaikipoodle20 Jul '08 - 9:51 
GeneralRe: Solution for using this technique with a user controlmemberkaan057 Aug '09 - 10:10 
GeneralRe: Solution for using this technique with a user controlmemberprincerc14 Feb '09 - 3:26 
QuestionIs it possible to call upload from a menu item?memberalan9317 Mar '08 - 3:11 
AnswerRe: Is it possible to call upload from a menu item?memberliammclennan17 Mar '08 - 10:16 
GeneralRe: Is it possible to call upload from a menu item?memberalan9318 Mar '08 - 6:34 
QuestionError when using postback triggermemberjeremygrand13 Dec '07 - 14:58 
GeneralThanks for the great tipsmemberJ Navaneethan27 Nov '07 - 4:57 
GeneralThanks for the infomemberaaron.barker9 Oct '07 - 13:57 
QuestionNot Shows the UpdateProgress [modified]membershan_y2005@yahoo.com30 Sep '07 - 20:51 
AnswerRe: Not Shows the UpdateProgressmembersupernont1 Nov '07 - 8:48 
NewsMore reliable waymemberbeep20 Aug '07 - 12:33 
GeneralRe: More reliable waymembermkushner21 Aug '07 - 18:40 
Questiontrigger control inside formview edit modemembershadstrife20 Jun '07 - 19:19 
AnswerRe: trigger control inside formview edit modememberBob Zebuilder20 Jun '07 - 22:14 
GeneralRe: trigger control inside formview edit modemembershadstrife21 Jun '07 - 15:02 
QuestionRe: trigger control inside formview edit modememberTxoov30 Jul '07 - 4:54 
AnswerRe: trigger control inside formview edit modememberbeefman16 Aug '07 - 3:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 30 Dec 2006
Article Copyright 2006 by liammclennan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid