简体   繁体   English

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

[英]How to send multiple image from MVC view to controller using Ajax in array format?

I am trying to send multiple images using Ajax but with out form data as my bunch of data is in array format.我正在尝试使用 Ajax 发送多个图像,但没有表单数据,因为我的一堆数据是数组格式。

my jquery function is,我的 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.");
                }
            });
        });

Above here I am sending same fields that I have in my sql table "Employee".在这里,我发送的字段与我的 sql 表“员工”中的字段相同。 I need to send two images from this array that are,我需要从这个数组发送两个图像,

   <input type="file" title="search image" id="EmpImage" name="file"/>
   <input type="file" title="search image" id="Document" name="file"/>

my controller is,我的控制器是,

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

Here I am getting all employee data need to send these images too在这里,我得到所有员工数据也需要发送这些图像

Hopes for your suggestions希望得到您的建议

Thanks谢谢

Now i am getting Images by using this code,现在我使用此代码获取图像,

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;

but still not able to get data passing in the form of object "customers"但仍然无法获得以对象“客户”形式传递的数据

Well, if your are using form element and your controls are inside the tag, you can simply serialize the whole form and append it to your FormData .好吧,如果您正在使用form元素并且您的控件在标签内,您可以简单地序列化整个form并将其附加到您的FormData This will also include any files generated with <input type="file" name="myImage" .../> :这还将包括使用<input type="file" name="myImage" .../>生成的任何文件:

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

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

Controller : Controller

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

If your model does not include a property for HttpPostedFileBase , then you can do:如果您的模型不包含HttpPostedFileBase的属性,那么您可以执行以下操作:

[HttpPost]
public ActionResult AddEmployee(List<Employee> Emp, HttpPostedFileBase EmpImage)
{
return Json();
}

Regarding your scenario since you are using plain HTML and without form I am assuming, your generated FormData looks correct so you would need to access your form data in your Controller with the associated tag that you have given to your model array like this:关于您的场景,因为您使用的是纯HTML并且没有我假设的form ,您生成的FormData看起来是正确的,因此您需要使用您为模型数组提供的关联标签访问Controller表单数据,如下所示:

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

There are two parts:有两个部分:

  • Build your ajax request on client-side在客户端构建您的 ajax 请求
  • Bind the request data to your model (using c# model binding) on server-side在服务器端将请求数据绑定到您的模型(使用 c# 模型绑定)

For the client side, you can find inspiration in this other post .对于客户端,您可以在另一篇文章中找到灵感。 Basically, do not forget to add the enctype="multipart/form-data to the <form> tag, and arrange the request data using the FormData JS class.基本上,不要忘记在<form>标签中添加enctype="multipart/form-data ,并使用FormData JS 类排列请求数据。

For the server side, use the IFormFile c# class in your model.对于服务器端,请在模型中使用IFormFile c# 类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM