Web Api 2 receive json array

∥☆過路亽.° 提交于 2019-12-12 17:34:22

问题


model

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

Send data

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

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?


回答1:


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

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.

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


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

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

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



来源:https://stackoverflow.com/questions/40106031/web-api-2-receive-json-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!