I'm having a problem when trying to upload file asynchronously from ajax to my controller. I have 3 variables to pass (PictureId, PictureName, and PictureFile). The problem lies on my "PictureFile" variable which should be holding the uploaded file itself but instead it always pass null value to the controller.
Here is my view model
public class PictureUpload
{
public int PictureId { get; set; }
public string PictureName { get; set; }
public HttpPostedFileBase PictureFile { get; set; }
}
Here is my controller
public JsonResult EditPicture(PictureUpload picture)
{
//do something here
}
Here is my form
<div class="thumbnail" id="uploadForm">
<form name="uploadForm" enctype="multipart/form-data">
<input type="text" name="fileId" hidden="hidden" />
<input type="file" name="file" style="max-width: 100%" />
<input type="button" name="cancel" value="cancel" />
<span>
<input type="button" name="upload" value="upload" />
</span>
</form>
</div>
Here is my script
$("input[name=upload]").click(function () {
var $pictureId = $("input[name=fileId]").val();
var $pictureFile = $("input[name=file]").get(0).files[0];
$.ajax({
type: 'POST',
url: '@Url.Action("EditPicture", "Restaurant")',
contentType: "application/json",
dataType: 'json',
data: JSON.stringify({ PictureId: $pictureId, PictureName: $pictureFile.name, PictureFile: $pictureFile }),
});
In my controller parameter. "PictureId" and "PictureName" holds the correct value, but "PictureFile" is always null. So it means something is going just not right when the system passes the parameter from ajax to controller. Somehow the system treats "file" type differently from others. Could you help me so the file get passed successfully to the controller and tell me what is wrong with this approach?