我的剧本:
//FILE UPLOAD
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: BASE_URL + "/BEHome/AddImgSlide/",
dataType: 'json',
data: $('#ImgSlideForm').serializeArray(), //SEND MODEL
beforeSend: function (xhr) {
//do something
},
success: function (data) {
//do something
},
error: function (data) {
//do something
}
});
我的控制器:
void AddImgSlide(ImageSlideModel model)
{
//do something
}
我正在尝试传递formData和$('#ImgSlideForm')。serializeArray()但不知道如何做到这一点。
任何帮助将不胜感激
答案 0 :(得分:2)
您可以使用FormData同时发送模型数据和文件,如下例所示:
<form id="create-form" >
Name: <input id="Name" type="text" name="Name">
<br />
Password: <input id="Edit-Password" type="password" name="Password">
<br />
<div>
<div>Upload Image</div>
<div>
<input type="file" name="UploadImage" id="UploadImage">
</div>
</div>
<input type="hidden" name="ImageId" id="ImageId" value="" />
<input type="hidden" name="UserId" id="UserId" value="" />
<input type="submit" id="SubmitBtn" />
</form>
<script>
$(document).ready(function(){
var formdata = new FormData();
var fileInput = document.getElementById("UploadImage");
formdata.append('Name', $('#Name').val());
formdata.append('Password', $('#Password').val());
if (fileInput.files.length > 0) {
formdata.append(fileInput.files[0].name, fileInput.files[0]);
}
$("#SubmitBtn").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: BASE_URL + "/BEHome/AddImgSlide/",
dataType: 'json',
data: formdata ,
contentType: false,
processData: false,
success: function (data) {
//do something
},
error: function (data) {
//do something
}
});
});
});
</script>
答案 1 :(得分:0)
您可以尝试将表单传递给FormData构造函数并将其作为数据发送
var formData = new FormData($('#ImgSlideForm')[0]);
$.ajax({
type: "POST",
url: BASE_URL + "/BEHome/AddImgSlide/",
dataType: 'json',
data: formData,
contentType: false,
processData: false,
beforeSend: function (xhr) {
//do something
},
success: function (data) {
//do something
},
error: function (data) {
//do something
}
});