I am using the MultiFile.js library when I am uploading files to ASP.Net MVC. http://www.fyneworks.com/jquery/multifile/
The problem is when I add a java-script listener in between to catch the JSON return value the my function in ASP see the files as null. If I do not use the java-script everything works as expected. I am wondering what I need to do to change what I am doing in java-script such that ASP still receives the files I am trying to upload.
The line below shows null for param attachments:
public ActionResult AttachFiles(IEnumerable<HttpPostedFileBase> attachments)
Java Script
$("#attachBtn").on("click", function (e) {
$(".has-success").removeClass("has-success");
$(".has-danger").removeClass("has-danger");
e.preventDefault();
const frm = $("#attachFiles");
$.post(frm.attr("action"), frm.serialize(), function (data) {
if (data.success) {
$("#alertMessage").addClass("alert-success");
$("#alertMessage #alertMessageText").text(data.message);
} else {
$("#alertMessage").addClass("alert-danger");
$("#alertMessage #alertMessageText").text(data.message);
}
});
});
$("#multiFileCustom").MultiFile({
list: "#attachmentList"
});
ASP.Net MVC
[HttpPost]
public ActionResult AttachFiles(IEnumerable<HttpPostedFileBase> attachments)
{
if (attachments == null || attachments.FirstOrDefault() == null)
{
return this.Json(new { success = false, message = "No files to attach" }, JsonRequestBehavior.AllowGet);
}
userAttachments = new List<string>();
foreach (var file in attachments)
{
if (file.ContentLength == 0)
{
continue;
}
var fullPath = AppDomain.CurrentDomain.BaseDirectory + @"App_Data\uploads\" + Path.GetFileName(file.FileName);
file.SaveAs(fullPath);
userAttachments.Add(fullPath);
}
return this.Json(new { success = true, message = "Files Attached" }, JsonRequestBehavior.AllowGet);
}
HTML
@using (Html.BeginForm("AttachFiles", "Home", FormMethod.Post, new { @id = "attachFiles", enctype = "multipart/form-data" }))
{
<div class="row">
<div class="form-group">
<label class="col-sm-1">Attach:</label>
<div class="col-sm-11">
<input type="file" id="multiFileCustom" name="attachments" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-offset-1" id="attachmentList"></div>
</div>
<div class="row">
<div class="col-sm-2 col-lg-offset-1">
<input type="submit" id="attachBtn" class="btn btn-default" value="Attach" />
</div>
</div>
}