简体   繁体   中英

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.

my jquery function is,

 $("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". 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 . This will also include any files generated with <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 :

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

If your model does not include a property for HttpPostedFileBase , then you can do:

[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:

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

There are two parts:

  • Build your ajax request on client-side
  • Bind the request data to your model (using c# model binding) on server-side

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.

For the server side, use the IFormFile c# class in your model.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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