$http post和ASP.NET MVC模型不绑定

6

为什么angularjs $http post的payload没有绑定到输入模型中?

当调用该操作时,模型为null,request.params和request.forms没有显示表单被发送的任何迹象。但是fiddler请求显示payload被以JSON形式发送。

AngularJS:

$http({
            method: "POST",
            url: "price/add",
            data: {
                Id: $scope.id,
                StoreId: $scope.storeid,
                Name: $scope.name,
                Manufacturer: $scope.manufacturer,
                Price: $scope.price
            }
        })

模型:

public class PriceModel
    {
        public int? Id { get; set; }
        public int? StoreId { get; set; }
        public string Barcode { get; set; }
        public string Name { get; set; }
        public string Manufacturer { get; set; }
        public DateTime Created { get; set; }
        public double? Price { get; set; }
    }

控制器和操作方法说明。
public class PriceController : Controller
    {
        [HttpPost]
        public int Add(PriceModel price)
        {

Fiddler:

POST http://localhost:4989/price/add HTTP/1.1
Host: localhost:4989
Connection: keep-alive
Content-Length: 70
Accept: application/json, text/plain, */*
Origin: http://localhost:4989
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:4989/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: nb,no;q=0.8,en-US;q=0.6,en;q=0.4

{"id":"","storeid":"","name":"asdf","manufacturer":"asdf","price":123}

4
不确定模型绑定是否会因参数名为“price”,而PriceModel中也有一个名为“Price”的属性而感到困惑。您可以尝试将操作参数的名称改为其他名称吗? - Andy T
你是正确的!发布答案并获得奖励 :) - Stian Standahl
2个回答

12

我不确定模型绑定是因为参数名为 price,而你在 PriceModel 中也有一个叫做 Price 的属性。你可以尝试重命名动作参数名称吗?


1
重命名参数名称非常有效!我将名称从“price”更改为“model”,然后它就起作用了。以前从未知道! - Stian Standahl
1
其他方面都看起来正确,唯有这一点有些可疑。很高兴它对你有所帮助! - Andy T

0
为了帮助其他人省去一个小时的麻烦,这个问题的一个普遍原因是使用了

http({
        url: url,
        method: 'POST',
        params: argument,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    }).success(function (data) {
        defered.resolve(data);
    }).error(function (data, status) {
        defered.reject(data);
    });

然而,如果我们改为以下方式,它就能完美运行:

http.post(
            url,
            argument
        ).success(function (data) {
            defered.resolve(data);
        }).error(function (data, status) {
            defered.reject(data);
        });


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接