2016-05-15 203 views
1

爲什麼在model變量中傳遞null?錯誤在哪裏?AngularJS將對象傳遞給控制器​​

enter image description here

控制器:

[HttpGet] 
    [AllowAnonymous] 
    public JsonResult LoginAngular(LoginViewModel model, string returnUrl) 
    { 
     Console.WriteLine(model.UserName); 
     return Json(model.UserName,JsonRequestBehavior.AllowGet); 
    } 

角:

var login = angular.module('LoginApp', []); 
login.controller('LoginCtrl', function ($scope, $http) { 
    $scope.name = 'Login'; 
    $scope.model = { UserName: 'nothing', Password: 'nothing' }; 
    $scope.model.UserName = "Test"; 
    $scope.model.Password = 'Test'; 
    $scope.returnUrl = '/Account/TestLogin'; 

    $scope.onClick = function() { 
     console.log($scope.model); 
     $http({ 
      method: 'GET', 
      url: '/Account/LoginAngular', 
      params: { model: $scope.model, returnUrl: $scope.returnUrl } 
     }).success(function (response) { 
      console.log(response); 
     }); 
    }; 
}); 
+0

從我understading 「得到」 是獲取數據, 「後」 是推送數據,所以你應該改變這一點。你也試圖將角模型映射到mvc模型。確保您的mvc視圖模型中定義的術語與您在角度中定義的完全匹配 –

+0

獲取請求沒有請求主體,您需要並且應該使用POST進行操作,例如登錄或註冊。 –

回答

1

請嘗試以下解決方案:

$http({ 
     url: '/Account/LoginAngular', 
     method: "POST", 
     data: {model: $scope.model, returnUrl: $scope.returnUrl}, 
     headers: { 
      "Content-Type": "application/json" 
     } 
    }).then(function(response) { 
     // success 
    }, 
    function(response) { // optional 
     // failed 
    }); 

或者你可以嘗試:

$http.post('/Account/LoginAngular',{model: $scope.model, returnUrl: $scope.returnUrl}) 
     .success(function (data, status, headers, config) { 
      //get response 
     }) 
     .error(function (data, status, header, config) { 
      //get error details 
     }); 
+1

使用'$ .param()'假定正在使用jQuery,它不應該用於''application/json'''。如果你想使用表單編碼,angular還有一個內置的序列化器,它不需要'$ .param()'。請參閱https://docs.angularjs.org/api/ng/service/$httpParamSerializerJQLike – charlietfl

+0

注意。謝謝你的信息。 –

0

使用POST方法來發送數據。

var login = angular.module('LoginApp', []); 
login.controller('LoginCtrl', function ($scope, $http) { 
$scope.name = 'Login'; 
$scope.model = { UserName: 'nothing', Password: 'nothing' }; 
$scope.model.UserName = "Test"; 
$scope.model.Password = 'Test'; 
$scope.returnUrl = '/Account/TestLogin'; 

$scope.onClick = function() { 
    console.log($scope.model); 
    $http({ 
     method: 'POST', 
     url: '/Account/LoginAngular?returnUrl=$scope.returnUrl', 
     data: $scope.model, 
    }).success(function (response) { 
     console.log(response); 
    }); 
    }; 
}); 
相關問題