Search code examples
asp.net-mvcpostuploadify

Post form and upload files sequence of events in MVC


I have a form with a number of fields and Uploadify to select and upload files. I have a javascript Submit method (called from the button click) that has the following:

$("#UrIntakeForm").submit();
$("#file_upload").uploadify("upload");

I then have two actions in my controller, one which receives an object to which the form data are mapped and another with the following signature that receives uploaded files:

public void UploadFile(HttpPostedFileBase fileData)

What I need to do is this:

  1. Save the form data to the database and get back an ID
  2. Insert a row into a table with each uploaded file's filename and an FK pointing to the first table
  3. Save the file somewhere
  4. Return a printable form with a confirmation number for the user to review

I'm a bit baffled at how to accomplish this sequence of events, however. First, the FileUpload action in the controller is getting called before the SaveForm action in the controller. Second, if the SaveForm action were called first, wouldn't returning the confirmation view prevent the files from uploading? I was told that the POST occurs in one fell swoop (files, form data, and all), but don't understand how I can have separate actions for saving the form and for file uploads if this is the case.

Can someone shed some light on what's going on behind the scenes with this POST (er, these posts) and how I can easily grab the uploaded data and do what I need with it? A 30,000-foot explanation should be perfect.


Solution

  • You need to upload the files first and pass back a reference to the file path or data for the main form to use when it submits. The modelbinder in MVC currently has pretty piss-poor to non-existent file handling support, so you unfortunately can't do it all in one pass.