To append array to FormData and send via Ajax with JavaScript, we can use the spread operator. const formData = new FormData(); const arr = ["this", "is", "an", "array"]; for (const a of arr) { formData. append("arr[]", a); } console. log(...
getAll() The getAll() method of the FormData interface returns all the values associated with a given key from within a FormData object. Note: This method is available in Web Workers.
set() The set() method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.
If your view is based on a model and you have generated the controls inside <form>
tags, then you can serialize the model to FormData
using
var formdata = new FormData($('form').get(0));
This will also include any files generated with <input type="file" name="myImage" .../>
and post it back using
$.ajax({
url: '@Url.Action("YourActionName", "YourControllerName")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
and in your controller
[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}
or (if your model does not include a property for HttpPostedFileBase
)
[HttpPost]
public ActionResult YourActionName(YourModelType model, HttpPostedFileBase myImage)
{
}
If you want to add additional information that is not in the form, then you can append it using
formdata.append('someProperty', 'SomeValue');
If you want to send Form data using Ajax.This is the way to send
var formData = new FormData();
//File Upload
var totalFiles = document.getElementById("Iupload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("Iupload").files[i];
formData.append("Document", file);
}
formData.append("NameCode", $('#SelecterID').val());
formData.append("AirLineCode", $('#SelecterID').val());
$.ajax({
url: "/Controller/ActionName",
type: "POST",
dataType: "JSON",
data: formData,
contentType: false,
processData: false,
success: function (result) {
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With