Chuyển đến nội dung chính

Binding mảng trong Javascript tới mảng trong C#

Để gởi 1 mảng dữ liệu (javascript array) từ client lên server, sử dụng ajax trong jquery, bạn có thể làm như sau:
    function sendData() {
        var ids = [1, 2, 3, 4];
        $.ajax({
            url: '@Url.Content("~/Home/Index")',
            data: { ids: ids },
            type: 'POST',
            success: function (data) {
                alert(data);
            }
        });
    }
Và thật lạ là trên Server, tham số ids luôn luôn bằng null
        [HttpPost]
        public ActionResult Index(IEnumerable<int> ids)
        {
            if (ids == null) return Json("Null Value");
            return Json(ids);
        }
Xem giá trị trong debug, ta thấy ids[] mới thật sự là tham số được truyền lên
debug on Server
Xem trong Firebug:
PostData1
Quá trình serialization trong Jquery bị sai. Nguyên nhân là vì: mặc định, dữ liệu gửi lên máy chủ được chuyển đổi thành chuỗi truy vấn.
Để gửi dữ liệu Javascript Object, bạn cần thiết lập tham số traditional = true
    function sendData() {
        var ids = [1, 2, 3, 4];
        $.ajax({
            url: '@Url.Content("~/Home/Index")',
            data: { ids: ids },
            type: 'POST',
            traditional: true,
            success: function (data) {
                alert(data);
            }
        });
    }
Và tham số khi post lên là ids

Tham khảo

processDataBoolean
Default: true
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

Nhận xét