c# - Web Api 2 接收 json 数组

标签 c# angularjs arrays json asp.net-web-api2

模型

public class modelVenta {
    public int idvendedor { get; set; }
    public int idcliente { get; set; }
    public int idproducto { get; set; }
    public int cantidad { get; set; }
    public decimal precio { get; set; }
    public DateTime fecha { get; set; }
}

public class modelVentas {
    public List<string> modeloVenta { get; set; }
}

Controller

[HttpPut]
[Route("api/ventas/Add")]
public HttpResponseMessage putVentas( List<modelVentas> data)
{
    return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

JSON

var data = [{
        "idvendedor": 1,
        "idcliente": 1,
        "idproducto": 1,
        "cantidad": 2,
        "precio": 12.0,
        "fecha": 1476445327124
    }, {
        "idvendedor": 1,
        "idcliente": 1,
        "idproducto": 2,
        "cantidad": 4,
        "precio": 23.0,
        "fecha": 1476445327124
    }, {
        "idvendedor": 1,
        "idcliente": 1,
        "idproducto": 1,
        "cantidad": 4,
        "precio": 35.0,
        "fecha": 1476445327124
    }];

发送数据

$http.put("http://localhost:54233/api/ventas/Add", JSON.stringify({
        modeloVenta: data
    })).then(function () {
        toastr.info('Elemento insertado correctamente');
    });

我验证了 http://jsonlint.com/ 中的 Json没关系,但每次我从 AngularJS 发送时,api Controller web 总是收到 Null。 请社区,有人可以帮我解决这个问题吗?

最佳答案

你的 putVentas()方法期待一个 List<modelVentas> - 使用 modelVentas简单地拥有 List<string> 的属性.

您发送的 JSON 实际上是一个 List<modelVenta> ,DefaultModelBinder 将尝试从它收到的 JSON 数据反序列化为您在签名中指定的类型。

这就是为什么 datanull ,因为它不会转换为方法签名所期望的类型。


您的 JSON 正试图传递 modelVenta 的列表方法。

要解决此问题,您需要更新 API 方法以匹配 JSON 发送的类型。将 API 方法的签名更改为:

public HttpResponseMessage putVentas(List<modelVenta> data)
{
    // do something with the data

    return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

你的 DefaultModelBinder 应该知道你正在传递 List<modelVenta>相反。

关于c# - Web Api 2 接收 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40106031/

相关文章:

AngularJs 在 $state 中使用解析和 ui-router

arrays - 将带有用户输入的 slice 附加到函数中

java - 如何将动态字符串值传递给方法?

c# - C# 中的神秘行

c# - 在单个 datagridview 中显示相关表中的数据

c# - 使用 MVVM 时如何使 TextBox 成为 "password box"并显示星星?

javascript - angularjs ng-repeat中的动态互斥下拉列表

c# - .NET2.0 C# 互操作 : How to call COM code from C#?

javascript - 我想使用 javascript 从 firebase 中删除元素

java - 用java将值输入到二维数组中