0

I have an aspx page with <input type='file'> elements. I want to use C# to save the files uploaded via these controls. I've seen certain solutions (like this one), which I can use in On_Load. Problem is my input controls will be created dynamically using JS, and I don't want a postback each time an image is uploaded.

Is there some equivalent method in C# to JS's .on() method, so that I can attach a handler to future controls?

EDIT: As suggested by @Oceans, I added an onchange event handler inside the input control:

<input type="file" onchange="saveFile" runat="server">

And I have a saveFile handler in my .cs behind:

protected void saveFile(object sender, EventArgs e)
{
    var imagesDir = Server.MapPath("Images/");
    var uploader = sender as FileUpload;
    uploader.PostedFile.SaveAs(imagesDir + uploader.PostedFile.FileName);
}

When I choose a file via the input control the function saveFile is not ran. I replaced onchange="saveFile" with onchange="alert('hi')" to check if the event is being fired and it is, so I'm obviously missing something... probably something to do with postback and .asp page cycle?

Community
  • 1
  • 1
OzW
  • 848
  • 1
  • 11
  • 24

1 Answers1

2

It seems to me that you're describing an EventHandler. Perhaps this tutorial about creating event handlers in an ASP.NET web form page might be of use to you.

If I understand you correctly, you wish to upload files as soon as they get selected. The html upload file control supports the onChange event to handle this. When creating the controls dynamically you should just define the onChange with it. For security reasons it's not really recommended to automatically upload files.

You'd get something like this:

<input type='file' onChange='MyEventHandler' runat='server'>

<script runat="server">
    protected void MyEventHandler(object sender, System.EventArgs e)
    {
        //do stuff
    }
</script>

I suggest you read the following documentation and as you seem familiar with JavaScript this might be of use to you aswell.

Oceans
  • 3,445
  • 2
  • 17
  • 38
  • I do no need to add `EventHandlers`, but how can I do this for elements that have not yet been created? JS's `.on()` does exactly that... and that's what I'm after. – OzW Sep 09 '15 at 20:29
  • I've edited my answer accordingly, I hope it helps you forward. – Oceans Sep 10 '15 at 07:46