【发布时间】: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。 -
另外,请注意
success/error方法已被弃用,建议改用then/catchpromise 方法。 -
更新了问题,对于 newChannel,我的意思是我会将我的频道名称存储到该对象中,然后我将其发布到我的属性名称频道中,但我肯定遗漏了导致我的问题的某些内容,但不确定是什么那
标签: javascript angularjs web asp.net-web-api