I am attempting to manually POST a form in ASP.NET Core using jQuery AJAX as soon as the user finishes selecting multiple files. The Uploader I am using has an "selected" event where I would like to POST the form to the server using jQueryAJAX.
This exact same form posts perfectly to the server when adding a submit button to the form and clicking it on the UI. The Files are bound and the ProductId is bound. However, I am trying to avoid the page flicker. As an alternative solution I am submitting the form by calling: $("#form").submit(); in the onSelect function rather than the AJAX request.
Model looks like the following:
public int ProductId { get; set; }
public IList<IFormFile> Files { get; set; }
Form looks like the following:
<form method="post" enctype="multipart/form-data">
<ejs-uploader id="Files" showFileList="false" autoUpload="false" multiple="true" selected="onSelected" success="onSuccess" allowedExtensions=".doc, .docx, .pdf, .jpg, .jpeg, .png"></ejs-uploader>
<input asp-for="ProductId" type="hidden" />
</form>
Here is the JavaScript that I have been trying which is not working:
function onSelected(args) {
var files = args.filesData;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files[]", files[i]);
}
$.ajax({
type: "POST",
contentType: false,
url: '?handler=FileUpload',
data: formData,
processData: false,
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (data) {
},
});
//$("#form").submit();
}
I am using razer pages so the action method is:
[BindProperty]
public int MessageId { get; set; }
[BindProperty]
public IList<IFormFile> Files { get; set; }
public async Task<ActionResult> OnPostAsync()
{
}
I have also tried creating a view model: FileUploadViewModel with the same 2 properties in it.
public async Task<ActionResult> OnPostAsync(FileUploadViewModel vm)
{
}
[FromForm] FileUploadViewModel vm, that might be the default thoughformData.append("Files", files[i]);