我在web api中使用PUT更新记录,当我使用contentType:' application / json; charset = utf-8',然后我的数据没有传递给api控制器,但是当我评论此行数据被转移时。任何人都能解释一下吗?下面是我从mvc视图的电话
$(function () {
$("#btnSubmit").click(function () {
var id = $("#hdnProductID").val();
var ProductName = $("#txtProductName").val();
var QuantityPerUnit = $("#txtQuantityPerUnit").val();
var ReorderLevel = $("#txtReorderLevel").val();
var UnitPrice = $("#txtUnitPrice").val();
var UnitsInStock = $("#txtUnitsInStock").val();
var UnitsOnOrder = $("#txtUnitsOnOrder").val();
$.ajax({
url: "http://localhost:2821/api/Products"+ "/" + id,
type: 'PUT',
contentType: 'application/json; charset=utf-8',
data:{ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder},
success: function (data) {
alert("success");
},
error: function (msg) {
alert(msg);
}
});
});
});
以下是我的控制器方法
public IHttpActionResult PutProduct(int id, Product product)
{}
答案 0 :(得分:2)
如果请求中未指定contentType,则采用默认的contentType,即“application / x-www-form-urlencoded; charset = UTF-8”,不需要对post数据进行stringfy,但如果contentType为“application” / json; charset = utf-8“,需要明确地发布数据。所以它应该是:
$.ajax({
url: "http://localhost:2821/api/Products"+ "/" + id,
type: 'PUT',
contentType: 'application/json; charset=utf-8',
data:JSON.stringify({ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder}),
success: function (data) {
alert("success");
},
error: function (msg) {
alert(msg);
}
});