这种情况:
我有一个表单,当我单击“提交”按钮时,将使用kendo上传控件发送文件,并且控制器的方法操作正在使用HttpPostedFileBase参数接收该文件。
这是我的HTML代码:
@using (Html.BeginForm("ConfirmarOposicion", "Gestion", FormMethod.Post, new { @id = "Frm-login", role = "form", @class = "form-horizontal" }))
{
@(Html.Kendo().Upload()
.Name("files")
)
<button class="btn btn-success" type="submit" id="confirm" >Confirm</button>
}
这是我的控制器:
public async Task<ActionResult> ConfirmarOposicion(IEnumerable<HttpPostedFileBase> files)
{
// Here the parameter files is not null..
}
到目前为止,这里一切都很好。问题是当我尝试将更多值作为参数发送到控制器的相同方法中时。
我要发送的其他值是一个数组,另一个是数字。
我尝试使用javaScript中的ajax发送这两个值。
当我尝试发送另外两个值时,这是我的javaScript代码:
$("#confirm").click(function () {
var numMarca = $("#numMarca").val()
var idsToSend = [];
var grid = $("#Grid2").data("kendoGrid")
var ds = grid.dataSource.view();
for (var i = 0; i < ds.length; i++) {
var row = grid.table.find("tr[data-uid='" + ds[i].uid + "']");
var checkbox = $(row).find(".checkbox");
if (checkbox.is(":checked")) {
idsToSend.push(ds[i].DescMarca);
idsToSend.push(ds[i].IntencionOposicion = 1);
} else {
idsToSend.push(ds[i].DescMarca);
}
}
$.ajax({
url: '@Url.Action("ConfirmarOposicion", "Gestion")',
data: { ids: idsToSend, marca: numMarca },
type: 'POST',
dataType: "json",
success: function (data) {
}
});
当我点击提交按钮时,将在我发送输入文件的同一控制器中发送这两个值。
现在,这是我的控制器:
public async Task<ActionResult> ConfirmarOposicion(IEnumerable<HttpPostedFileBase> files, string[] ids, string marca)
{
// here the array ids and the value of marca is not null, but the parameter files it is null
}
这就是我的问题。
我需要在控制器的相同方法操作中发送所有这些值。
我怎样才能做到这一点?
最佳答案
问题:这行代码是data: { ids: idsToSend, marca: numMarca },
您正在手动构建仅具有两个参数的数据对象,并且不处理上传的文件,因此文件数据丢失。
解决方案:构建一个FormData
对象,然后将所有必需的数据(包括您上载的文件)塞入其中,然后将该对象发送到服务器。
var formData = new FormData();
var file_data = $('#files')[0].files; // for multiple files if only single file use $('#files')[0].files[0] and skip the loop.
for(var i = 0;i<file_data.length;i++){
formData.append("file_"+i, file_data[i]);
}
formData.append('ids', idsToSend);
formData.append('marca', numMarca );
$.ajax({
url: '@Url.Action("ConfirmarOposicion", "Gestion")',
data: formData , // pass the formData object to server.
type: 'POST',
processData: false,
contentType: false,
dataType: "json",
success: function (data) {
}
});
注意:
$('#files')
获取文件控件,kendo语法中的.Name("files")
将文件控件的ID设置为files
。编辑:我添加了
processData: false,
和contentType: false,
到ajax选项。归功于this answer将processData设置为false可以防止jQuery自动将数据转换为查询字符串。有关更多信息,请参见the docs。
必须将
contentType
设置为false,因为否则jQuery will set it incorrectly。关于javascript - 当我发送其他值作为参数时,Kendo Upload文件在 Controller 中发送null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40719890/