$ http帖子没有与asp.net MVC模型绑定

时间:2014-03-13 20:58:49

标签: asp.net-mvc angularjs asp.net-mvc-4

为什么来自angularjs $ http帖子的有效负载没有绑定到输入模型?

当调用该操作时,模型为null,并且request.params和request.forms不显示任何表单发送的迹象。但是小提琴请求表明有效载荷是用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}

2 个答案:

答案 0 :(得分:12)

我不确定模型绑定是否会混淆,因为参数名为price,并且PriceModel中的属性也称为Price。您可以尝试重命名动作参数名称吗?

答案 1 :(得分: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);
        });