我正在使用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)
{}
data:JSON.stringify({ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder})
。 - T JcontentType: 'application/json; charset=utf-8',
是有效的吗?你尝试过只使用contentType: 'application/json;'
吗?参考这个链接:https://dev59.com/cXRB5IYBdhLWcg3w4bKv - zer00nedata
中没有传递任何JSON格式的数据。 - t.niese