2015-10-05 55 views
2

我创建了一个web服务,可以用多行发布新订单。Web API 2多个嵌套模型

模式

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

控制器

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

     return "Foo"; 
    } 
} 

有了邮递员我创建一个JSON POST请求是这样的:

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

当我运行在Visual调试器Studio,Order模型从请求中填充,但OrderLine为NULL。当我改变

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

public OrderLine OrderLine {get; set;} 

我的JSON字符串在邮递员

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

我的模型被填充,当我发布的数据。我想发布一个OrderLines的集合。我究竟做错了什么?

回答

0

要发布的OrderLine阵列,使得你的请求需要包含一个数组:

"OrderLine" : [{}, {}] 

,它应该是这样的:

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