C# 如何使用阵列格式的Ajax将多个图像从MVC视图发送到控制器?
我尝试使用Ajax发送多个图像,但没有表单数据,因为我的数据是数组格式的 我的jquery函数是C# 如何使用阵列格式的Ajax将多个图像从MVC视图发送到控制器?,c#,json,ajax,image,model-view-controller,C#,Json,Ajax,Image,Model View Controller,我尝试使用Ajax发送多个图像,但没有表单数据,因为我的数据是数组格式的 我的jquery函数是 $("body").on("click", "#btnSave", function () { //Loop through the Table rows and build a JSON array. var customers = new Array(); var row = $(this);
$("body").on("click", "#btnSave", function () {
//Loop through the Table rows and build a JSON array.
var customers = new Array();
var row = $(this);
var files1 = $("#file").get(0).files;
var customer = {};
alert(files1);
customer.EmpPic = "";
customer.FirstName = txtFirstName.value;
customer.SecondName = txtSecondName.value;
customer.ThirdName = txtThirdName.value;
customer.Tribe = ddltribe.value;
customer.NationalID = txtNationalId.value;
customer.Address = txtAddress.value;
customer.Location = ddlcityy.value;
customer.Education = txtEducation.value;
customer.PhoneNumber = txtPhoneNo.value;
customer.FamilyTree = "";
customer.SignaturePath ="";
customer.StempPath = "";
customer.StempChangePath = "";
customer.FamilyCertificatePath = "";
customer.IBAN = txtIban.value;
customer.IBANPath = "";
customers.push(customer);
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Home/AddEmployee",
data: JSON.stringify(customers),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
在这里,我发送的字段与我的sql表“Employee”中的字段相同。我需要从这个阵列发送两个图像
<input type="file" title="search image" id="EmpImage" name="file"/>
<input type="file" title="search image" id="Document" name="file"/>
但是仍然无法以对象“客户”的形式获得数据传递。有两部分:
- 在客户端构建ajax请求
- 将请求数据绑定到服务器端的模型(使用c#模型绑定)
enctype=“multipart/form data
添加到
标记中,并使用FormData
JS类排列请求数据
对于服务器端,在模型中使用ifformfile
c#类
公共类员工{
...
公共文件EmpPic{get;set;}
公共文件文档{get;set;}
}
好的,如果您使用的是表单
元素,并且您的控件在标记中,您可以简单地序列化整个表单
,并将其附加到表单数据
中。这还将包括使用
生成的任何文件:
控制器
:
[HttpPost]
public JsonResult AddEmployee(List<Employee> Emp)
{
return Json();
}
关于您的场景,因为您使用的是普通的HTML
而没有form
,我假设,您生成的FormData
看起来是正确的,因此您需要访问Controller
中的表单数据,并使用您为模型数组提供的相关标记,如下所示:
var emp = Request.Form["mydata"];
你的情况是什么?是用户上传的图像,显示在页面上,然后你想将它们保存到数据库中,还是…?@mortb我在帖子中的错误我提到了标签没有添加我有输入类型文件我需要将其与我的数据一起传递给控制器。我不想显示我使用的是simplehtml@Doc尝试以下操作:
Request.Form.GetValues(“mydata“;
或请求。在控制器
侧的表单[“mydata”]
。我刚刚做了这个var emp=Request。表单[“mydata”];它工作了!
var formdata = new FormData($('form').get(0));
$.ajax({
url: '@Url.Action("AddEmployee", "Home")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
[HttpPost]
public JsonResult AddEmployee(List<Employee> Emp)
{
return Json();
}
[HttpPost]
public ActionResult AddEmployee(List<Employee> Emp, HttpPostedFileBase EmpImage)
{
return Json();
}
var emp = Request.Form["mydata"];