First, use ajax to replace the original form submission method, you need to add event.preventDefault();
to the click event to prevent the default form submission method from occurring.
I am try to upload files, need to pass files from ajax call to
controller,but issue is i need to pass files along with model object
,which is creating issue.
To solve it, you can use the following two methods to pass parameters by ajax:
Use var fdata = new FormData($('#form').get(0));
to get all the
model data in the form.
Split the ModelObject as an array and then take fields by name and
value one by one:
var ModelObject = $('#form').serializeArray();
for (var i = 0; i < ModelObject.length; i++) {
fdata.append(ModelObject[i].name, ModelObject[i].value);
}
Here is complete code:
Model:
public class UploadVm
{
public int ID { get; set; }
public string Name { get; set; }
}
Controller:
[HttpPost]
public IActionResult Index(IFormFile files, UploadVm model)
{
return View();
}
View:
<form id="form" method="post" enctype="multipart/form-data">
ID:<input type="text" name="ID" id="id" /><br>
Name:<input type="text" name="Name" id="name" /><br>
File:<input type="file" id="postedFile" /><br>
<input type="submit" name="submit" id="upload" value="Submit" />
</form>
@section Scripts
{
<script>
$("#upload").click(function (e) {
event.preventDefault();
var files = $("#postedFile").get(0).files;
var fdata = new FormData($('#form').get(0));//the first way
for (var i = 0; i < files.length; i++) {
fdata.append("files", files[i]);
};
//the second way
//var ModelObject = $('#form').serializeArray();
//for (var i = 0; i < ModelObject.length; i++) {
// fdata.append(ModelObject[i].name, ModelObject[i].value);
//}
$.ajax({
url: '/Home/Index',
data: fdata,
dataType: "json",
async: false,
type: 'POST',
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function (xhr, ajaxOptions, error) {
alert("error!");
}
});
});
</script>
}
You can also refer to this.
Here is the test result:
