Web Api 2 接收 json 数组 [英] Web Api 2 receive json array

查看:33
本文介绍了Web Api 2 接收 json 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

型号

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; }
}

控制器

[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 控制器 web,总是接收 Null.请社区,有人可以帮我解决这个问题吗?

I validate the Json in http://jsonlint.com/ and is ok, but every time I send from AngularJS, api controller web, always receives Null. please community, someone could help me solve this problem?

推荐答案

你的 putVentas() 方法需要一个 List - With a modelVentas 仅具有 List 的属性.

Your putVentas() method is expecting a List<modelVentas> - With a modelVentas simply having a property of List<string>.

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

Your JSON that you're sending is actually a List<modelVenta>, which the DefaultModelBinder will try and deserialize to the type you've specified in the signature, from the JSON data it receives.

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

This is why data is null, as it doesn't translate to the type the method signature is expecting.

您的 JSON 正在尝试将 modelVenta 列表传递给该方法.

Your JSON is trying to pass a list of modelVenta to the method.

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

To fix this, you will need to update the API method to match the type that JSON is sending. Change your signature of the API method to be:

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

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

并且您的 DefaultModelBinder 应该知道您正在传递一个 List.

And your DefaultModelBinder should pick up that you're passing a List<modelVenta> instead.

这篇关于Web Api 2 接收 json 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆