Search code examples
c#jqueryhtmlasp.netjsajaxfileuploader

How do you pass HTML input files to C# ASP.Net using AjaxFileUpload.js?


I'm new to stackoverflow so my apologies if I misuse any of the guidelines. I am in the middle of making a ASP.Net website and I have run into a very specific problem where I am using ProcessRequest to try and retrieve multiple files.

C# ASP.Net Code

The variable files is not retreiving requested files context.Request.Files

public void ProcessRequest(HttpContext context)
{
     try
     {
          var files = context.Request.Files;

          for (int i = 0; i < files.Count; i++)
          {
               //Checking to see if the files exist
               var postedFile = files[i];
          }
     }
     catch (Exception e)
     {
          context.Response.Write(e.Message);
     }
}

I am trying to avoid refreshing the web page and types of submit to allow the user to navigate through the content fluently. I believe my problem stems from dynamically adding my input file html elements from the C# backend.

HTML

<div id='fmAddFiles'>
    <input id='fileUploader' type='file' multiple='true' runat='server'/>
    <input id='addFilesBtn' type='button' value='Add Files'/>
</div>
<div id='fmSubmit'><input id='uploadBtn' type='button' value='Upload'/></div>

I have bound click and trigger events for addFilesBtn and fileUploader and they get hit correctly. It is when I attempt to pass the files to the backend using $.ajaxFileUpload that nothing happens.

$.ajaxFileUpload({
     url: 'WebHandler.ashx',
     async: false,
     secureuri: false,
     fileElementId: 'fileUploader',
     dataType: 'json',
     success: function (data, status) {
          alert(data);
     },
     error: function (data, status, e) {
          alert(e);
     }
});

All the mentioned functions get hit just I can't for the life of me can't figure out why it is not retrieving any of the files.

Where might I be going wrong?

EDIT

I tried adding static elements to my html and found out that the server control does not work when dynamically adding elements. The runat='server' tag no longer works when this is done.

Now I am a crossroads. Is there a way to bind the server control to an element or am I going to have to use a bunch of CSS tricks? Which to me is rather messy at the best of times.


Solution

  • I had a bit of a light bulb moment before where I realised that I was already hiding fileUploader. All I did was made it static and made sure the selectors used the server control ID so that uploadBtn was able to trigger it.

    Also had a look at Prasad Raja's answer thoroughly as well and would recommend anyone starting a new project to consider it. Was very insightful.