【问题标题】:Angular JS Not Sending Data To Web ApiAngular JS 不向 Web Api 发送数据
【发布时间】:2016-10-28 23:52:47
【问题描述】:

Angular Post 方法不向 Web api 控制器发送数据。 $http 调用 web api 但它为空。

【问题讨论】:

  • 使用 ng-model insted of data-ng-model,让我知道
  • 是的,我认为 Rakeschand 是对的,你需要初始化,让我来投票

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


【解决方案1】:

先定义(初始化)$FirstNameLastNameEmailNumber 为 null。

$scope.FirstName = null;
$scope.LastName = null;
$scope.Email = null;
$scope.Number = null;

或者你可以直接使用$scope.user

$scope.user = {
    id : 0,
    FirstName : null,
    LastName : null,
    Email : null,
    Password : null
};

并将ng-model作为user.FirstName传入

编辑:

CreateUser 函数之外构建$scope.user

$scope.CreatUser=function(){
   $http{(...)};
}

结束

【讨论】:

  • $scope.FirstName = null; $scope.LastName = null; $scope.Email = null; $scope.Number = null; $scope.User = { Id:'0', FirstName: '', LastName: '', EMail: '', Password: '', Mobile:'0' };
  • $scope.CreateUser = function () { debugger; $http({ method: 'POST', dataType:'json', url: 'localhost:50048/api/SingUp/Post', data: $scope.User, headers: { 'Content-Type': 'application/x-www-form-urlencoded ' }, }).then(function successCallback(response) { $scope.productsData.push(response.data); $scope.clear(); alert("Successfully !!!"); }, function errorCallback(response) { }); };
  • 我已经更改了我的代码,但它仍然传递 null ,我还删除了数据,现在我只使用 ng-model。
  • 在 CreateUser 函数外构建 $scope.user,它在 CreateUser 方法内重新启动
【解决方案2】:

将 $scope.User 移动到控制器范围:

app.controller('myCtrl',function($scope,$http){
   $scope.User = {
    id : 0,
    FirstName : null,
    LastName : null,
    Email : null,
    Password : null
    };

    $scope.CreatUser=function(){
      $http{(...)};
    }

})

并将 ng-model 作为 User.FirstName 传入。

【讨论】:

  • 依赖于你发送给我的这个,i.stack.imgur.com/1gjyS.png,你做的不对。您需要删除 CreatUser 函数中的 $scope.user
  • 如果 m 不发送模型并且 m 发送 sting 值但仍然发送 null。你能检查一下标题和内容类型的值吗?
  • 我将使用完整代码编辑我上面的答案,请稍等
  • 公开 httpResponsMessage Post([FromBody] SignUpView DataFromUI){
  • 我也尝试过 Post([FromBody] SignUpView DataFromUI) 但它不起作用。
【解决方案3】:
protected void Application_BeginRequest() {
  if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS"){
    Response.Flush();
  }
}

【讨论】:

    【解决方案4】:

    您正面临此问题,因为您的标头请求 content-type 是:application/x-www-form-urlencoded,它将无法正常工作。试试改成application/json

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-30
      • 2021-09-21
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-17
      • 2013-07-07
      相关资源
      最近更新 更多