Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

c# - Web Api 2 receive json array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...