简体   繁体   中英

Send array of Objects to MVC Controller

I try to send an array of json objects to server:

var objectData = [
    {  Description: "Bezeichnung", Value: "1", Name: "Betrag (Brutto)" },
    { Description: "Dies ist die erste Bezeicnung", Value: "101", Name: "11,90" },
    { Description: "Dies ist die zweite Bezeicnung", Value: "12", Name: "11,90" }
];

$.ajax({
    url: "/system/createinvoice",
    data: JSON.stringify({ pos: objectData }) ,
    dataType: 'json',
    type: 'POST',
});

C#

public class InvoicePos
{
    public string Description { get; set; }
    public Nullable<double> Value { get; set; }
    public string Name { get; set; } 
}

[POST("/system/createinvoice")]
public void newquestion2(InvoicePos[] pos)
{
   // pos is always null       
}

The dataType property is saying what you expect back from the server. Try setting the contentType :

contentType: 'application/json'

Try

data: JSON.stringify({ pos: @objectData })

Also, check what is being rendered in the View through the browser. The reason you are getting null is likely because JavaScript is not getting a proper value.

function SendArrayOfObjects() { var things = [{ id: 1, color: 'red' }, { id: 2, color: 'blue' }, { id: 3, color: 'yellow' }];

          $.ajax({
            type: "POST",
            url: "<%= ResolveUrl("~/MyServices.aspx/GetData")%>",
              data: JSON.stringify({ objdata: things }),
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function()
            {
                $("#msg").html("data sent successfully!");
            },
            error: function()
            {

                $("#msg").html(" Can not send data!");
            }
        });


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM