简体   繁体   中英

Sending an array or list to asp.net mvc controller using jquery

I have a project to find a place with Asp.Net MVC. The purpose of my project is to find latitude and longitude collectively according to the address column in the excel file. I use axios to find latitude and longitude by address. When I select the excel file I want, it is saved in the database. I want to find the latitude and longitude of the addresses in excel and save them in the database. I used the series in Console.log to see the data I wanted and I was successful, but there is a continuous recording going to the controller. I want to go to the controller as a list or as a series. Where am I doing wrong? Is there anyone who can help me?

This is my javascript code:

$('input[type="file"]').change(function (e) {
        handleFileSelect(e);
    });

    function handleFileSelect(evt) {

        var files = evt.target.files; // FileList object
        var xl2json = new ExcelToJSON();
        xl2json.parseExcel(files[0]);
    }

    function getLatLng(address, fn) {
        axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
            params: {
                address: address,
                key: 'apiKey'
            }
        }).then(function (response) {
            fn(response.data.results[0].geometry.location.lat, response.data.results[0].geometry.location.lng);
        })
        //axios.get({ 'address': address }, function (results, status) {
        //    fn(results[0].geometry.location.lat(), results[0].geometry.location.lng());
        //});
    }

    var ExcelToJSON = function () {

        this.parseExcel = function (file) {
            var reader = new FileReader();

            reader.onload = function (e) {
                var data = e.target.result;
                var workbook = XLSX.read(data, {
                    type: 'binary'
                });

                workbook.SheetNames.forEach(function (sheetName) {
                    // Here is your object
                    var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
                    var json_object = JSON.stringify(XL_row_object);
                    console.log(json_object);
                    var d = JSON.parse(json_object);
                    console.log(d);




                    for (var i = 0; i <= d.length; i++) {

                        $.each(d[i + 1], function (IndexNo, Deger) {
                            console.log(Deger);

                            getLatLng(d[i + 1].Adres, function (lat, lng) {
                                if (lat != '' && lng != '') {
                                    console.log(lat);
                                    console.log(lng);
                                }

                                var maps = [
                                    { lat:lat },
                                    { lng: lng }
                                ];

                                maps = JSON.stringify({ 'maps': maps });

                                console.log(maps);

                                var maplist = new Array();

                                maplist[0] = lat;
                                maplist[1] = lng;

                                var postData = { value: maplist };

                                  var maplst = new Array();
                                var map;
                                $.each(maplist,function () {
                                    map = {};
                                    map.Latitude = maplist[0];
                                    map.Longitude = maplist[1];
                                    maplst.push(map);
                                    console.log(map);
                                    document.getElementById('items').value = map;
                                });
                            });

                        });

                    }

                })

            };

            reader.onerror = function (ex) {
                console.log(ex);
            };

            reader.readAsBinaryString(file);
        };
    };

This is my controller:

[HttpPost]
    public ActionResult Index(FormCollection formCollection, string[] items)
    {
        LocationDBEntities db = new LocationDBEntities();
        List<AWSServerless_Google_Geocoding_Mvc.Models.Map> mapList = new List<AWSServerless_Google_Geocoding_Mvc.Models.Map>();
        mapList = new List<AWSServerless_Google_Geocoding_Mvc.Models.Map>();
        if (Request != null)
        {
            HttpPostedFileBase file = Request.Files["FileUpload"];
            if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
            {
                string fileName = file.FileName;
                string fileContentType = file.ContentType;
                byte[] fileBytes = new byte[file.ContentLength];
                var path = Path.Combine(Server.MapPath("~/Content/FileUpload"), file.FileName);
                file.SaveAs(path);
                var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
                if (db.Map.Where(x => x.FileName == fileName).Any())
                {
                    TempData["Message"] = "Aynı isimden dosya mevcut.";
                    ViewBag.Path = path;
                    return View();
                }
                else
                {
                    using (var package = new ExcelPackage(file.InputStream))
                    {
                        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                        var currentSheet = package.Workbook.Worksheets;
                        var workSheet = currentSheet.First();
                        var noOfCol = workSheet.Dimension.End.Column;
                        var noOfRow = workSheet.Dimension.End.Row;
                        for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
                        {
                            var map = new Map();
                            map.UserID = Convert.ToInt32(Session["UserID"]);
                            for (int i = 0; i < items.Length; i++)
                            {
                                map.Latitude = items[0];
                                map.Longitude = items[1];
                            }
                            map.Address = workSheet.Cells[rowIterator, 3].Value.ToString();
                            map.ExcelPath = path;
                            map.FileName = fileName;
                            map.LastFileName = Request.Cookies["sonYuklenenDosya"].Value;
                            map.PrevFileName = Request.Cookies["oncekiYuklenenDosya"].Value;
                            map.BeforeFileName = Request.Cookies["dahaOncekiYuklenenDosya"].Value;
                            map.ModifyUserId = Convert.ToInt32(Session["UserID"]);
                            map.ModifyUser = Session["FirstName"].ToString();
                            map.ModifyDate = DateTime.Now;
                            map.CreateUserId = Convert.ToInt32(Session["UserID"]);
                            map.CreateHost = Session["FirstName"].ToString();
                            map.CreateDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
                            mapList.Add(map);
                            map.FileCount = mapList.Count;
                        }
                    }
                }

            }
        }
        foreach (var item in mapList)
        {
            db.Map.Add(item);
        }
        db.SaveChanges();
        return View(mapList);

enter image description here

Please help me.

Javascript:

var stringArray = new Array();
stringArray[0] = "item1";
stringArray[1] = "item2";
stringArray[2] = "item3";
var postData = { values: stringArray };

$.ajax({
    type: "POST",
    url: "/Home/SaveList",
    data: postData,
    success: function(data){
        alert(data.Result);
    },
    dataType: "json",
    traditional: true
});

Controller:

public JsonResult SaveList(List<String> values)
{
  //code...
}

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