我的ajax调用让我的web.api方法变得麻烦.如果我从api和js中删除了Guid orderId,则调用将其发送给控制器,但是pizza对象为空.如果我在URL中传递Guid,它也会转到控制器但没有披萨.请解释为什么这不起作用或帮助我使其工作.
JS:
var savePizza = function (orderId,pizza) {
var dataCall = $.ajax(config.savePizzaUrl,{
data: ko.toJSON({ orderId: orderId,pizza: pizza }),type: "post",contentType: "application/json"
});
return Q.when(dataCall);
};
Web Api:
[HttpPost]
public RequestReturn
JS对象:
var pizza = function (data) {
this.Id = data.Id;
this.Size = new size(data.Size);
this.SizeId = data.SizeId;
this.Toppings = $.map(data.Toppings,function(item) {return new topping(item);});
};
var topping = function (data) {
this.Id = data.Id;
this.Name = data.Name;
this.Price = data.Price;
};
var size = function (data) {
this.Id = data.Id;
this.Name = data.Name;
this.Price = data.Price;
};
C#对象:
public class Pizza
{
public Guid Id { get; set; }
public Guid SizeId { get; set; }
public Size Size { get; set; }
public IEnumerable
JSON Fiddler Post Capture:
最佳答案
默认情况下,ASP.NET Web API将请求主体绑定到复杂类型(在您的情况下为Pizza). Web API将整个主体绑定到一个参数.诸如GUID的简单类型从URI路径和查询字符串绑定.因此,通过在URI中传递GUID并仅发布与披萨对象相对应的JSON(仅披萨而不是订单ID等其他任何东西),您可以使其正常工作.