【问题标题】:how to post data to server using angularJS, web api如何使用 angularJS、web api 将数据发布到服务器
【发布时间】:2016-10-11 13:42:20
【问题描述】:

我是 angularJS 的新手,想弄清楚如何将数据发布到我的服务器,问题是我的发布到服务器是成功的,它会创建新记录,但一切都是空的(null)。

感谢您的建议

JS:

    $scope.addChannel = function () {
    var channels = [];
    //var newChannel = {
    //    Name: $scope.Name
    //};
    //clearing error message
    $scope.errorMessage = "";

    $http.post("api/Channel/channels", newChannel)
        .success(function (newChannel) {
            //on success
            $scope.channels.push({ "Name": $scope.Name });
            console.log("data added");
           // newChannel.push(response.data);
            newChannel = {};
        }, function () {
            //on failure
            $scope.errorMessage = "Failed to save data";
        })
}

HTML:

<div ng-controller="ChannelController">
<div class="col-md-4 col-lg-4 col-sm-4">
    <form novalidate name="newUser"ng-submit="addChannel()">
        <div class="form-group">
            <label for="name">Channel</label>
            <input class="form-control" type="text" id="Name" name="Name" ng-model="newChannel.Name" />
        </div>
        <div class="form-group">
            <input type="submit" value="Add" class="btn btn-success" />
        </div>
    </form>
    <a ng-href="/Dashboard#/channels">Return to dashboard</a>
</div>
<div class="has-error" ng-show="errorMessage">
    {{errorMessage}}
</div>

频道控制器

        [HttpPost("channels")]
    public async System.Threading.Tasks.Task Create(Channel channel)
    {
        await _channelRepository.CreateChannel(channel);
    }

存储库

        public async System.Threading.Tasks.Task CreateChannel(Channel channel)
    {
        _context.Channel.Add(channel);
        await _context.SaveChangesAsync();
    }

【问题讨论】:

  • 请把webapi方法也贴出来
  • 传递给 $http.post 的 newChannel 是什么?您的数据位于$scope.newChannel.Name
  • 检查成功回调签名:docs.angularjs.org/api/ng/service/$http
  • 另外,请注意success/error 方法已被弃用,建议改用then/catch promise 方法。
  • 更新了问题,对于 newChannel,我的意思是我会将我的频道名称存储到该对象中,然后我将其发布到我的属性名称频道中,但我肯定遗漏了导致我的问题的某些内容,但不确定是什么那

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


【解决方案1】:

检查您在发送到服务器的对象中是否正确命名属性,属性名称区分大小写。看起来你在js中

var customer = {name: 'foo', lastName: 'bar'};

在服务器上,您尝试将 JSON 反序列化为该实体

class Customer {
  public Name {get;set;} //note prop names are capitalized
  public LastName {get;set;}
}

【讨论】:

  • 属性名称应该是正确的,我使用每个模型属性的首字母大写
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-27
  • 1970-01-01
  • 2012-05-29
  • 2013-08-07
  • 1970-01-01
  • 2018-04-27
相关资源
最近更新 更多