【问题标题】:$http method: "post" not passing data$http 方法:“post”不传递数据
【发布时间】:2015-10-29 16:47:54
【问题描述】:

我像这样使用 Angular 的 $http:

$http({
                url: '/api/Movies/UpdateMovie',
                method: "POST",
                data: movie,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

            })

检查客户端我看到电影已正确填充,但是当向服务器发送数据时,电影模型没有填充已发布的数据(或者可能没有数据发布到它),我使用 web api 进行服务。另外我在服务器上的电影模型是:

 public class Movie
{
    public int Id { get; set; }

    [Required]
    [StringLength(256, ErrorMessage = "Maximum Title length is 256.")]
    public string Title { get; set; }

    [Required]
    [StringLength(256, ErrorMessage = "Maximum Director length is 256.")]
    public string Director { get; set; }

    [Required]        
    public decimal Price { get; set; }
}

如何将电影作为数据传递?

【问题讨论】:

标签: asp.net angularjs asp.net-web-api


【解决方案1】:

您可以将您的对象解析为表单数据,也许这个要点 https://gist.github.com/ghinda/8442a57f22099bdb2e34 对您有用,无论如何您可以将内容类型更改为 application/json,如下所示:

标头:{ 'Content-Type': 'application/json' }

【讨论】:

    【解决方案2】:

    使用此功能:

      var param = function (obj) {
            var query = '', name, value, fullSubName, subName, subValue, innerObj, i; for (name in obj) {
                value = obj[name]; if (value instanceof Array) {
                    for (i = 0; i < value.length; ++i)
                    { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; }
                } else if (value instanceof Object) {
                    for (subName in value)
                    { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; }
                } else if (value !== undefined && value !== null) query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
            } return query.length ? query.substr(0, query.length - 1) : query;
        };   // Override $http service's default transformRequest  $httpProvider.defaults.transformRequest = [function(data) {    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;  }];}); 
    

    和设置

    data: param(logOn), headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    

    现在可以了。

    【讨论】:

    • 但在我的情况下,一种更好的方法是在 web api 的参数前面放置 [FromBody] 属性并将数据作为 Json 发送。
    【解决方案3】:

    在您的代码中尝试:

    var movie = {};
    movie.Title = "Title";
    movie.Director = "Director";
    movie.Price = 0.50;
    

    并删除:headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

    $http({
       url: '/api/Movies/UpdateMovie',
       method: "POST",
       data: movie
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 2016-05-29
      • 2017-10-13
      • 2011-02-27
      • 1970-01-01
      相关资源
      最近更新 更多