【问题标题】:Post Javascript Array to WebAPI将 Javascript 数组发布到 WebAPI
【发布时间】:2014-03-19 01:03:39
【问题描述】:

我想将 Javascript 数组发布到 WebAPI。

我有我的 Javascript 数组,例如:

var checkedGroups = [];
var checkedStaff = [];

$.each(items, function () {

    if (this.checked) {
        type = dataAdapter.records[this.id - 1].VALUETYPE;
        if (type == 'Staff') {
            checkedStaff[checkedStaff.length] = this.value;
        } else {
            checkedGroups[checkedGroups.length] = this.value;
        }
    }
});

然后我使用这个将它发送到我的 WebAPI:

data: { staff: JSON.stringify(checkedStaff) };

我的 WebAPI 控制器是这样的:

public HttpResponseMessage Post([FromBody] formData data)
{
    string string_group = String.Join(",", data.group);
    string string_staff = String.Join(",", data.staff); 
}

我的 formData 类是这样的:

public class formData
{
    public Array group { get; set; }
    public Array staff { get; set; }
}

如上所述,我想将数组拆分成一个逗号分隔的字符串。

但服务器端的 string_staff 变量只是一个空字符串,我的 JSON 数据是这样的:

staff: "["1"]"
group: ""

我也不想在数组中使用键/值类型。

有什么想法吗?

【问题讨论】:

  • 也许尝试将您的组和员工属性更改为 string[]int[] 而不是 Array
  • 嗨,是的,我在发布问题之前确实将其作为字符串,但未尝试过 string[] 明天会试一试
  • WebAPI 处理数据绑定的方式与 MVC 不同。试试这个data: { '': myArray },其中 myArray 有一个用于员工的属性和一个用于组的属性。然后创建一个 ViewModel(具有两个数组属性,一个用于人员,一个用于组),然后将其设置为方法的传入参数类型。

标签: javascript jquery arrays json asp.net-web-api


【解决方案1】:

将checkedGroups 和checkedStaff 变量更改为对象字面量。 Javascript 中并没有像您尝试设置它的方式那样的关联数组。

var checkedGroups = {};
var checkedStaff = {};

$.each(items, function () {

    if (this.checked) {
        type = dataAdapter.records[this.id - 1].VALUETYPE;
        if (type == 'Staff') {
            checkedStaff[checkedStaff.length] = this.value;
        } else {
            checkedGroups[checkedGroups.length] = this.value;
        }
    }
});

如果这样做,您可以将它们保留为数组:

checkedStaff.push(this.value);

【讨论】:

    【解决方案2】:

    一般来说,你应该使用jQuery ajax 函数$.ajax({ ... }) 来发布到WebAPI 控制器。我发现这种方法效果最好:

    function postJSON(data)
    {
      return $.ajax({
        url: '/api/xyz',
        type: 'POST',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8" // must have this option set
      });
    }
    
    function doSomethingElse() {
    
      postJSON({ staff: checkedStaff, group: checkedGroup })
        .done(function(response) { ... });
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-22
      • 2019-03-30
      • 1970-01-01
      • 2018-07-12
      • 2015-02-16
      • 2016-10-07
      • 2019-01-30
      • 1970-01-01
      相关资源
      最近更新 更多