在我的 html 代码中,我有一个文件(没有表单标签)
<input id="file1" type="file" class="form-control form-exception">
和一些文本框
<input id="id-one" type="text" class="form-control" >
<input id="id-two" type="text" class="form-control" >
...
<input id="id-six" type="text" class="form-control" >
...
C# 中的代码隐藏
public class Model
{
public int Id { get; set; }
public Dictionary<string, string> Fields { get; set; }
public string File { get; set; }
}
public ActionResult Send(Model myModel)
{
...
}
我想将数据从 html 发送到我的 Controller :Id, Dictionary<html id,html value>
和文件。
此解决方案不起作用:
var dict={
'[0].Key':'id-one'.
'[0].Value':'aaaaa'
}
var data = new FormData();
data.append('Id', @Model.Id);
data.append('Fields', dict);
data.append('File',$('#file1')[0].files[0]);
$.ajax({
url: '@Url.Action("Send")',
type: 'POST',
data: data,
dataType: 'json',
contentType: false,
processData: false,
complete: function (data) {
},
error: function (response) {
}
});
此代码适用于文件,但不适用于字典
我该如何解决这个问题?提前致谢!!!
最佳答案
您无法使用 .append()
将对象添加到 FormData
,只能添加简单值。您需要单独添加每个名称/值对。
var data = new FormData();
data.append('Id', @Model.Id);
data.append('Fields[0].Key', 'id-one'); // add the dictionary key
data.append('Fields[0].Value', 'aaaaa'); // add the dictionary value
data.append(File, $('#file1')[0].files[0]);
$.ajax({
....
});
我假设您实际上想使用 id="id-one"
发布输入的值,在这种情况下它是 data.append('Fields[0].Value' , $('#id-one').val());
此外,正如 Chris Pratt 的回答所述,您发布了文件输入的值,因此您在模型中的属性应该是
public HttpPostedFileBase File { get; set; }
关于c# - 如何使用ajax发送字典和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42115810/