Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API 2 multiple nested models

I'm creating a webservice where one can post a new order with multiple lines.

Models

public class Order {

    public int OrderID { get; set; }
    public string Description { get; set; }
    public string Account { get; set; }
    public ICollection<OrderLine> OrderLine { get; set; }

}

public class OrderLine {
    public int OrderLineID { get; set; }
    public int OrderID { get; set; }
    public string Product { get; set; }
    public double Price { get; set; }
}

Controller

public class OrderController : ApiController
{
    [HttpPost]
    public string Create(Order order)
    {
        OrderRepository or = new OrderRepository();

        return "Foo";
    }
}

With Postman I create a post request in Json like this:

{"Description" : "Abc", "Account" : "MyAccount",
    "OrderLine[0]" : {
        "ItemCode": "Item1",
        "Price" : "10"
    } 
}

When I run the debugger in Visual Studio, The Order model is populated from the request, but OrderLine is NULL. When I change

public ICollection<OrderLine> OrderLine {get; set;}

to

public OrderLine OrderLine {get; set;}

And my Json string in Postman to

{"Description" : "Abc", "YourReference" : "yourABC", "Account" : "AB1010",
    "OrderLine" : {
        "ItemCode": "Item1",
        "Price" : "10"
    }
}

My model gets populated when I post the data. I want to post a collection of OrderLines. What am I doing wrong?

like image 763
kwv84 Avatar asked Jan 28 '26 14:01

kwv84


1 Answers

You're POSTing an array of OrderLine so your request needs to contain an array:

"OrderLine" : [{}, {}]

and it should look like this:

{"Description" : "Abc", "YourReference" : "yourABC", "Account" : "AB1010",
    "OrderLine" : [{
        "ItemCode": "Item1",
        "Price" : "10"
    },
   {
        "ItemCode": "Item2",
        "Price" : "20"
    }]
}
like image 193
LeftyX Avatar answered Jan 30 '26 11:01

LeftyX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!