[英]Data is always null when send from view to web api controller
當我從視圖向Web API控制器發送數據時,我的ID字段在控制器中始終為空,以下是我的代碼
$scope.Create_Click = function (CategoryselectedItemvalue, SupplierSelectedItemvalue, Product_Name, Quantity_PerUnit, Reorder_Level, Unit_Price, Units_InStock, Units_OnOrder) {
var CategoryID = parseInt(CategoryselectedItemvalue);
var SupplierID = parseInt(SupplierSelectedItemvalue);
var ProductName;
var QuantityPerUnit;
var ReorderLevel;
var UnitPrice;
var UnitsInStock;
var UnitsOnOrder;
Product = {
CategoryID: CategoryID,
SupplierID: SupplierID,
ProductName: Product_Name,
QuantityPerUnit: Quantity_PerUnit,
ReorderLevel: Reorder_Level,
UnitPrice: Unit_Price,
UnitsInStock: Units_InStock,
UnitsOnOrder: Units_OnOrder
};
$http({
method: 'POST',
url: '/api/Products/PostProduct',
data: JSON.stringify($scope.Product),
headers: { 'Content-Type': 'application/JSON' }
}).
success(function (data) {
alert("Record Added");
}).
error(function (msg) {
alert(msg);
});
};
});
下面是我的控制器方法(在這里,當我收到數據CategoryID並且SupplierID始終為null時)
[ActionName("PostProduct")]
public IHttpActionResult PostProduct(Product product)
{
Product pro = new Product();
pro.CategoryID = product.CategoryID;
pro.SupplierID = product.SupplierID;
pro.ProductName = product.ProductName;
pro.QuantityPerUnit = product.QuantityPerUnit;
pro.ReorderLevel = product.ReorderLevel;
pro.UnitPrice = product.UnitPrice;
pro.UnitsInStock = product.UnitsInStock;
pro.UnitsOnOrder = product.UnitsOnOrder;
if (repo.AddNewProduct(pro))
{
return Ok("Product Added");
}
else
{
return Ok("Error");
}
}
在對數據進行字符串化時,它應為JSON格式,其鍵為product
(操作參數名稱)
data: JSON.stringify({product : $scope.Product}),
或者,如果您使用的是Web.API
,則無需對數據進行字符串化Web.API
,只需在操作Product
參數之前使用[FromBody]
屬性即可。
[ActionName("PostProduct")]
public IHttpActionResult PostProduct([FromBody] Product product)
{
//code is the same
}
由於您的標頭是'application / json',因此我認為不需要使用JSON.stringify
,它基本上將json轉換為字符串,因此您無法訪問鍵。
只需以JSON格式發送對象即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.