【问题标题】:$http post not binding with asp.net MVC model$http post 未与 asp.net MVC 模型绑定
【发布时间】:2014-04-18 21:42:51
【问题描述】:

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

当调用该操作时,模型为空,并且 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)
        {

提琴手:

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}

【问题讨论】:

  • 我不确定模型绑定是否混淆,因为参数名为 price 并且您在 PriceModel 中有一个属性,也称为 Price。您可以尝试重命名操作参数名称吗?
  • 你是对的!发布答案并获得奖励:)

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


【解决方案1】:

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

【讨论】:

  • 重命名参数名称很有魅力!我将名称从价格更改为型号,并且有效。从来不知道!
  • 其他一切似乎都是正确的,这是唯一看起来可疑的事情。很高兴它有帮助!
【解决方案2】:

只是为了节省另一个人一个小时,这个问题的一个普遍原因是我们在使用时

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

【讨论】:

    猜你喜欢
    • 2013-02-20
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多