Im using ASP.NET MVC5. My goal was to upload file using jQuery ajax. When successful, return a partial view of the uploaded files in a table. When I step through the jQuery code, the id and files are correct, but when stepped into Action, both parameters are null. Here are my codes:
Controller's Action:
[HttpPost]
public ActionResult AddAttachments(string id, IEnumerable< HttpPostedFileBase> files)
{
if (files != null)
{
//save files
}
var cardKey = db.CardKeys.Single(s => s.CardKeyID == Convert.ToInt32(id));
var attachments = cardKey.Request.Attachments;
return PartialView("_AttachmentsTable",attachments);
}
jQuery:
$(function () {
var table = $("#attachmentTable").DataTable();
var path = MySettings.addAttachmentURL;
$("#btnAddAttachment").click(function (event) {
event.preventDefault();
var formData = new FormData();
var cardKeyID = $("#CardKeyID").val();
var formData = $.each($("#files")[0].files, function (i, file) {
formData.append('file-' + i, file);
});
console.log("formData = " + formData);
$.ajax({
type: "POST",
url: path,
contentType: false,
processData:false,
cache:false,
data: {id:cardKeyID,files: formData },
success: function (partialResult) {
$("#tableData").html(partialResult);
table = $("#attachmentTable").DataTable();
},
error: function (jqXHR, textStatus, errorThrown) {
$("#message").html(JSON.stringify(jqXHR).toString());
alert("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
});
Razor View:
<fieldset>
<legend>Add Attachments</legend>
<div class="row">
<div class="col-md-4">
<div class="form-group">
@Html.Label("File Upload", new { @class = "control-label col-md-6" })
<div class="col-md-6">
<input type="file" id="files" name="files" multiple/><br />
<input type="submit" id="btnAddAttachment" value="Add Attachment"/>
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
@Html.Label("File Description", new { @class = "control-label col-md-6" })
<div class="col-md-6">
@Html.TextBox("FileDescription")
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
@Html.Label("Comment", new { @class = "control-label col-md-6" })
<div class="col-md-6">
@Html.TextBox("Comment")
</div>
</div>
</div>
</div>
<div id="tableData">
@Html.Partial("_AttachmentsTable",Model.Request.Attachments)
</div>
</fieldset>