I have a form where user can add one or more attachment using this code
<div id="attachments">
</div>
<a href="#" id="addAttachment">Add attachment</a>
<script>
$("#addAttachment").click(function () {
var strChooseFile = "<table><tr><td><input type='file' name='PostedFiles' size='30' title='Choose file ...'></td>";
strChooseFile += "<td><input type='text' name='FileDescriptions' size='50' title='File descriptions ...'></td>";
strChooseFile += "<td><input type='button' name='btnAttachmentRemove' id='btnRemoveAttachment' value='Remove' ></td></tr></table>";
inputFile = $(strChooseFile);
inputFile.clone(true).appendTo("#attachments");
});
</script>
I followed this tutorial to prepare the data before being sent to the server. Below the code how I prepared the data:
$("#btnAddInvoice").click(function (e) {
if ($("#frmInvoice").validate().form()) {
var m_data = new FormData();
m_data.append("SubsidiaryClientID", $("#SubsidiaryClientID").val());
m_data.append("SubsidiaryClientNo", $("#SubsidiaryClientNo").val());
m_data.append("SubsidiaryClientName", $("#SubsidiaryClientName").val());
m_data.append("PostedFiles", $("input[name=PostedFiles]").val()); // how to parse this to json?
m_data.append("FileDescriptions", $("input[name=FileDescriptions]").val()); // how to parse this to json?
$.ajax({
type: "POST",
url: "@Url.Content("~/Invoice/AddInvoice")",
data: m_data,
contentType: false,
processData: false,
dataType: "json",
cache: false
}).done(function (data) {
alert(data);
if (!data.message) {
$("#invoiceList").html(data);
$("#addInvoiceModal").modal("hide");
}
});
}
});
As you can see in the code above, I've a problem when prepared PostedFiles
and FileDescriptions
. After being sent to the controller, the values is null.
How to prepared PostedFiles
from array of $("input[name=PostedFiles]")
and also FileDescriptions
?