从视图发送到web api控制器时,数据始终为null
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始终为空时)
[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
}
相关文章:
- delete在Object上效率低下,但在DOM Element's的数据属性,与null out相比
- 在php中提交数据时,如果某些值为null,而某些值为非null,如何进行查询
- javascript对象显示为null,但object.properties返回数据
- 为什么我发布的数据在这个AJAX调用的Controller目标中为null
- 电话间隙.正在向数据库表中插入Null值.数据类型冲突
- MVC 控制器正在从具有数据的 JavaScript 对象传入 null
- 纯 JS 获取所选选项数据属性值返回 Null
- 尝试将使用 SQL 语句生成的 JSON 数据从 PHP 脚本返回到 JS 网页,但改为 null
- 当变量的数据类型在 javascript 中为 'Null'
- Node.js在返回数据之前返回null的函数/实现回调
- 除非访问了数据属性,否则Blaze.getData(el)将返回null
- jQuery数据表-ASP.NET控制器参数始终为null
- 从ajax数据中获取null
- 处理Rally数据存储中的null异常
- MVC控制器'发布JSON数据时,s字符串[]参数为null
- '数据'为null或不是对象IE8
- 从视图发送到web api控制器时,数据始终为null
- 只有当数据为数字或null时,才会触发删除GridView中的行时使用数据进行确认
- 传递的角度UI模态数据为null
- JSON格式的Ajax源数据-无法获取属性'长度'的未定义引用或null引用