locked
Sending an array with hidden field to the controller using jquery RRS feed

  • Question

  • User-2003602335 posted

    I want to send an array to the controller using jquery. Continuous data is going on. I want to go to the controller as a list or as an array. Who can help me?

    This is my controller:

    [HttpPost]
            public ActionResult Index(FormCollection formCollection, string[] items)
            {
                LocationDBEntities db = new LocationDBEntities();
                List<Map> mapList = new List<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));
                            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 < noOfRow; i++)
                                    {
                                        map.Latitude = items[i];
                                        map.Longitude = items[i];
                                    }                           
                                    map.Address = workSheet.Cells[rowIterator, 3].Value.ToString();
                                }
                            }
                        }
                    }
                }
                foreach (var item in mapList)
                {
                    db.Map.Add(item);
                }
                db.SaveChanges();
                return View(mapList);

    This is my javascript code:

    var liste, i, listeUzunluk;
        liste = [
           { lat: lat },
           { lng: lng }
        ];
        listeUzunluk = liste.length;
        for (i = 0; i < listeUzunluk; i++) {
            console.log(liste[i]);
            document.getElementById("items").value = liste[i];
        }

    Where am I doing wrong? What should I do?

    Sunday, July 19, 2020 7:40 PM

All replies

  • User-939850651 posted

    Hi emre.senturk,

    If you want to pass an array as a parameter to the controller, using jQuery.ajax() would be a good way.

    I wrote a simple example, the following is the code:

    Model:
    
    public class Map
        {
            public int userid { get; set; }
            public string username { get; set; }
            public string gender { get; set; }
            public string password { get; set; }
        }
    js code:
    
    $(document).ready(function () {
                var array = [];
                for (var i = 0; i < 5; i++) {
                    var user = {
                        userid: "userID" + i,
                        username: "userName" + i,
                        gender: "male" + i,
                        password: "password" + i
                    }
                    array.push(user);
                }
                $.ajax({
                    url: '@Url.Action("ArrayToController")',
                    type: 'post',
                    data: {
                        UserList: array
                        //param:'test string'
                    },
                    dataType: 'json',
                    success: function (response) {
                        if (response != null) {
                            for (var i = 0; i < response.length; i++) {
                                console.log(response[i])
                            }
                        }
                    },
                    error: function () {
                        alert("there is something wrong..")
                    }
                })
            });
    Controller:
    
    [HttpPost]
            [ActionName("ArrayToController")]
            public ActionResult getArray(List<Map> UserList) {
                List<string> result = new List<string>();
                //loop the UserList
                foreach (Map m in UserList)
                {
                    string str = "Hello There, " + m.username;
                    result.Add(str);
                }
    
                return Json(result);
            }

    Result:

    Hope this can help you.

    Best regards,

    Xudong Peng

    Monday, July 20, 2020 6:23 AM
  • User-2003602335 posted

    Hello, thank you for your example. I understood your code. But what I want is to capture the data that I can see in console.log as a list or series on the controller and save it to the database, respectively.

    The values ​​I caught in Console.log:

    Monday, July 20, 2020 11:43 AM
  • User-939850651 posted

    Hi emre.senturk,

    You didn't seem to pass the array data to the controller correctly. Before passing the data to the controller, you should ensure that the data is correct.

    I think you may need to modify its structure appropriately. like this:

    public class Map
        {
            public double lat { get; set; }
            public double lng { get; set; }
        }
    $(document).ready(function () {
                var array = [{ lat: 41.07941330000001, lng: 28.8538545 },
                             { lat: 41.081402, lng: 28.9819771 },
                             { lat: 41.03357099999999, lng: 28.903377 }];
    
                $.ajax({
                    url: '@Url.Action("ArrayToController")',
                    type: 'post',
                    data: {
                        items: array
                    },
                    dataType: 'json',
                    success: function (response) {
                        if (response != null) {
                            console.log(response)
                        }
                    },
                    error: function () {
                        alert("there is something wrong..")
                    }
                })
            });
            [HttpPost]
            [ActionName("ArrayToController")]
            public ActionResult getArray(List<Map> items) {
                List<string> result = new List<string>();
                //loop the UserList
                foreach (Map m in items)
                {
                    string str = "lat --> " + m.lat.ToString() + "  lng --> " + m.lng.ToString();
                    result.Add(str);
                }
                return Json(result);
            }

    In controller, I will get data:

    And result:

    Best regards,

    Xudong Peng

    Tuesday, July 21, 2020 7:21 AM