您可以将其他输入字段值添加到 FormData 对象。
我首先创建一个视图模型来接受 ajax 负载
public class UploadVm
{
public string Type { set; get; }
public string Id { set; get; }
public HttpPostedFileBase File { set; get; }
}
现在在您的视图中,添加 2 个输入元素以从用户读取此值
<input id="id" type="text" />
<input id="type" type="text" />
现在,在您的 ajax 调用代码中,再添加 2 个项目FormData
object.
$("#start_upload").click(function (evt) {
var fileUpload = $("#file-upload").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append("File", files[i]);
}
//Add the input element values
data.append("Type", $("#type").val());
data.append("Id", $("#id").val());
$.ajax({
type: "POST",
url: "/Products/UploadFiles",
contentType: false,
processData: false,
data: data,
success: function (message) {
console.log(message);
},
error: function () {
alert("There was error uploading files!");
}
});
});
现在在您的服务器端,您可以使用我们的新视图模型作为操作方法的参数。当进行ajax调用时,模型绑定器将能够映射从请求接收到的数据并将其映射到我们的属性UploadVm
查看模型对象。
[HttpPost]
public ActionResult UploadFiles(UploadVm model)
{
// to do : read values of model and use it
// to do : return something
}