I want to post three things to my MVC Controller: one image and two strings.
On the View, I've got a form that uses enctype="multipart/form-data" that automatically submits the form after an image file is selected. This is the submit handler for this form:
$("#PhotoUploadForm").on("submit", function (event) {
event.preventDefault();
var ImageData = $("#PhotoUploadFileInput").val();
var GuestNumber = $("#GuestID").val();
var TCSA_ID = vm.GetSelectedTreatmentAreaTCSA_ID(vm.Photographs.SelectedTreatmentArea());
var dto = {
ImageData: ImageData,
GuestNumber: GuestNumber,
TCSA_ID: TCSA_ID
}
$.ajax({
url: 'SaveImage',
type: "POST",
contentType: "multipart/form-data",
data: ko.toJSON(dto),
success: function (data) {
console.log(submitted);
}
});
});
The dto object is defined in my Model:
public class PhotoUploadDTO
{
public HttpPostedFileBase ImageData { get; set; }
public string GuestNumber { get; set; }
public string TCSA_ID { get; set; }
}
And in my Controller, I have an action that takes in dto as a parameter:
public ActionResult SaveImage(PhotoUploadDTO dto)
{
//etc.
}
When I try to post dto, everything gets posted as null. This problematic for me because I want to be able to post the image and two strings to the controller simultaneously.
I suspect that the issue is with var ImageData (which is set to the value of <input type="file" id="PhotoUploadFileInput"> on my View), and that it is being posted as C:/fakepath/etc. but not as the actual image file. It's frustrating because I know it wouldn't even be an issue if I had a form that just posted the image, but I need to use this submit handler and I don't know how to bring the actual image data into it.
Why is the data null when it hits the MVC Controller, and how can I post these three items while still being able to use a submit handler?
XMLHttpRequestsendAsBinary()or theFile APIfor new browsers.