【发布时间】:2017-08-11 19:23:43
【问题描述】:
以前,我只需要创建一个表单,其中只包含要发送到动作的数据而不是图像,现在,我遇到了将数据与图像一起发布到动作的要求。我不知道如何将图像附加到数据中,以便我可以让它继续工作。
这就是我将数据和图像一起发布的方式,但我收到null 的实际操作:
HTML
<input type="file" id="profilePic" name="file" value="Browse">
<input type="text" id="EmployeeCode" name="EmployeeCode" value="EmployeeCode">
<input type="text" id="SystemCode" name="SystemCode" value="SystemCode">
<input type="button" value="Create" onclick="SaveEmpData()" />
我知道如何获取输入类型的文本数据并通过ajax请求以json格式发送并将其保存到数据库,但是当涉及到通过ajax请求以json格式获取数据和图像时,我'不知道如何做到这一点。
JS
var empdata = { "SystemCode": "", "EmployeeCode": "" };
empdata.EmployeeCode = $("#EmployeeCode").val();
empdata.SystemCode = $("#SystemCode").val();
var data = new FormData();
var files = $("#profilePic").get(0).files;
data.append("Image", files[0]);
Ajax
$.ajax({
url: '/EmployeeMasterA/Create',
headers: headers,
data: JSON.stringify({ employeeMasterA: empdata, profilePic: data }),
type: 'POST',
dataType: 'json',
contentType: 'application/json',
traditional: true,
success: function (result) {
if (result.Success == "1") {
window.location.href = "/EmployeeMasterA/Index";
}
else {
alert(result.ex);
}
}
});
和Create 行动:
[HttpPost]
public ActionResult Create([Bind(Include = "SystemCode,EmployeeCode")] EmployeeMasterA employeeMasterA, HttpPostedFileBase profilePic)
{
var pic = System.Web.HttpContext.Current.Request.Files["Image"];
}
在上面的代码中,pic 变量是null。我的问题是:
从表单中获取数据+图像并通过 ajax 请求将其发送到操作的正确方法是什么?任何帮助都深表感谢:)
更新
在参考了liran的回答后,我尝试通过这种方式编辑我的代码进行绑定:
JS
var empbind = { "profilePic" : "", "employeeMasterA" : "" };
// Created empdata and data (image) object as mentioned above
empbind.employeeMasterA = empdata;
empbind.profilePic = data;
var empbindjson = JSON.stringify(empbind);
并更改了 Ajax data 参数如下:
$.ajax({
.
.
data: empbindjson,
.
.
});
并更改了我的控制器操作:
[HttpPost]
public ActionResult Create([Bind(Include = "employeeMasterA,profilePic")] EmployeeBind bind)
{
var pic = System.Web.HttpContext.Current.Request.Files["Image"];
}
employeeMasterA,profilePic 在上述代码的调试模式下都收到null,这是我的新绑定类:
public class EmployeeBind
{
public EmployeeMasterA employeeMasterA { get; set; }
public HttpPostedFileBase profilePic { get; set; }
}
好的,现在,我已更改代码以将其与profilePic 绑定,我做错了什么吗?因为create action 的bind 参数都包含employeeMasterA 和profilePic 的null。
【问题讨论】:
-
您需要使用
FormData并设置正确的ajax 选项。
标签: jquery json ajax asp.net-mvc image-uploading