A191919
A191919

Reputation: 3462

AngularJS pass object to controller

Why it's pass null in model variable? Where is mistake?

enter image description here

Controller:

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

Angular:

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);
        });
    };
});

Upvotes: 2

Views: 4983

Answers (2)

Karthik M R
Karthik M R

Reputation: 990

Use POST method to send the data.

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);
    });
  };
});

Upvotes: 0

Conrad Lotz
Conrad Lotz

Reputation: 8838

Try the following solution:

  $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
    });

Alternatively you can try:

   $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
        });

Upvotes: 1

Related Questions