2016-05-15 6 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 "'に使うべきではありません。 angleは、フォームエンコーディングを使いたい場合に '$ 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); 
    }); 
    }; 
}); 
関連する問題