【发布时间】:2016-05-29 21:11:12
【问题描述】:
我有一个简单的测试来尝试理解 $http.post 从 AngularJS 到 ASP.NET WebAPI。帖子成功,但在 API 上收到的值显示为空。我已经对此进行了测试,发现 $scope 对象在发布之前拥有一个值。
我到处检查,发现 ASP.NET WebAPI 以奇怪的方式处理帖子数据。
这是我获取输入的 HTML 代码,Basic.html:
<form name="basicItem" novalidate ng-app="app" ng-controller="ItemCtrl">
<label id="titlelabel" class="required">Title</label>
<input ng-model="item.Title" type="text" id="titlefield" name="Title"
required />
这是来自 ItemController.js 的代码,用于检查验证和帖子(我使用的是 CORS,因为这两个程序都有单独的域):
app.controller("ItemCtrl", ['$scope', '$http', function ($scope, $http) {
$scope.submitForm = function (form) {
if (form.$valid) { //If Title has some value
item = {
"Title": $scope.item.Title, //Set "Title" to the user input
}
alert($scope.item.Title); //This shows that my value is not null
$http.post("http://localhost:50261",
{
testTitle: $scope.item.Title //!!!Probably the problem, sets
}).success(function (result) { //the parameter of API post
alert('Success!');
}).error(function (data) {
alert("Valid but didn't connect");
console.log(data);
})
这是 API 控制器中的代码,EntryController.cs:
[HttpPost]
public string CreateEntry([FromBody]string testTitle)
{
return testTitle; //returns null!!!
}
我已经阅读了关于需要 [FromBody] 并且只使用 1 个简单参数的信息。最后,我还看到我应该将我的帖子值用引号括起来或给出一个前导的“=”符号,但这两种方法似乎都不起作用。任何帮助或建议都会很重要。
【问题讨论】:
-
您是否尝试过返回硬编码字符串值以隔离 Action 绑定值或客户端中的问题?只需使用
return "ThisIsATest"来验证问题出在哪里并告诉我们结果。
标签: javascript c# asp.net angularjs asp.net-web-api