从视图发送到web api控制器时,数据始终为null

Data is always null when send from view to web api controller

本文关键字:数据 null 控制器 视图 api web      更新时间:2023-09-26

当我将数据从视图发送到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始终为空时)

[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");
            }
        }

由于您的头是"application/json",我认为不需要使用JSON.stringify,它基本上将json转换为字符串,因此您无法访问密钥。

只需以JSON格式原样发送对象即可。

字符串化数据时,它应该是JSON格式,其中它的密钥是product(操作参数名称)

data: JSON.stringify({product : $scope.Product}),

或者,如果使用Web.API,则不需要字符串化数据,只需要在使用Product参数之前使用[FromBody]属性即可。

[ActionName("PostProduct")]
public IHttpActionResult PostProduct([FromBody] Product product)
{
   //code is the same
}