如何使用 Ajax 以数组格式将多个图像从 MVC 视图发送到控制器?

Posted

技术标签:

【中文标题】如何使用 Ajax 以数组格式将多个图像从 MVC 视图发送到控制器?【英文标题】:How to send multiple image from MVC view to controller using Ajax in array format? 【发布时间】:2020-06-17 19:35:29 【问题描述】:

我正在尝试使用 Ajax 发送多个图像,但没有表单数据,因为我的一堆数据是数组格式。

我的 jquery 函数是,

 $("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"/>

我的控制器是,

 public JsonResult AddEmployee(List<Employee> Emp)
                        
                return Json();            
        

我在这里获取所有员工数据也需要发送这些图像

希望您的建议

谢谢

现在我正在使用此代码获取图像,

var formData = new FormData();
            var profile = $("#EmpImage").get(0).files;
            var Iban = $("#Document").get(0).files;



            //setting ArrayData to Json Object
            formData.append("mydata", JSON.stringify(customers));
            formData.append("EmpImage", profile[0]);
            formData.append("Document", Iban[0]);

HttpPostedFileBase EmpImage= Request.Files["EmpImage"];
            HttpPostedFileBase Document= Request.Files["Document"];
            var data = Request.Form;
            return null;

但仍然无法获取以对象“客户”形式传递的数据

【问题讨论】:

你的方案是什么?是用户上传的图片,显示在页面上,然后要保存到数据库,还是……? @mortb 我在帖子中的错误我提到 标记不是我添加的我有输入类型文件我需要将它与我的数据一起传递给控制器​​。我不想展示它 【参考方案1】:

好吧,如果您正在使用form 元素并且您的控件在标签内,您可以简单地序列化整个form 并将其附加到您的FormData。这还将包括使用&lt;input type="file" name="myImage" .../&gt; 生成的任何文件:

var formdata = new FormData($('form').get(0));

$.ajax(
  url: '@Url.Action("AddEmployee", "Home")',
  type: 'POST',
  data: formdata,
  processData: false,
  contentType: false,         
);

Controller:

[HttpPost]
public JsonResult AddEmployee(List<Employee> Emp)
                
  return Json();            

如果您的模型不包含 HttpPostedFileBase 的属性,那么您可以这样做:

[HttpPost]
public ActionResult AddEmployee(List<Employee> Emp, HttpPostedFileBase EmpImage)

return Json();

关于您的场景,因为您使用的是普通的 html 而没有 form 我假设您生成的 FormData 看起来是正确的,因此您需要使用您的关联标签访问您的 Controller 中的表单数据给你的模型数组是这样的:

var emp = Request.Form["mydata"];

【讨论】:

我使用的是简单的html @Doc 试试这个:Request.Form.GetValues("mydata");Request.Form["mydata"]Controller 一侧。 我刚刚做了这个 var emp = Request.Form["mydata"];成功了!【参考方案2】:

分为两部分:

在客户端构建您的 ajax 请求 在服务器端将请求数据绑定到您的模型(使用 c# 模型绑定)

对于客户端,您可以在this other post 中找到灵感。 基本上不要忘记将enctype="multipart/form-data添加到&lt;form&gt;标签中,并使用FormData JS类排列请求数据。

对于服务器端,在您的模型中使用IFormFile c# 类。

public class Employee 
    ...
    public IFormFile EmpPic  get; set; 
    public IFormFile Document get; set; 

【讨论】:

以上是关于如何使用 Ajax 以数组格式将多个图像从 MVC 视图发送到控制器?的主要内容,如果未能解决你的问题,请参考以下文章