Search code examples
javascriptc#angularjsangular-http

pass data from http request to C# controller


My problem is when I pass the data to C# controller my loginInfo is null payload is ok and show stringify loginfo but my method do not get logInfo.

Service

comaxApp.factory('user', function($http) {
  return {
    login: function(loginInfo) {
      $http({
        url: './data/LogIn',
        method: "POST",
        data: loginInfo,
        headers: {
          'Content-Type': 'application/json'
        }
      }).success(function(data, status, headers, config) {
        $scope.users = data.users;
      }).error(function(data, status, headers, config) {
        $scope.status = status + ' ' + headers;
      });
    }
  };
});

Controller

$scope.login = function() {
    var loginInfo = {
        "user": "admin",
        "password": "123"
    };
    loginInfo = JSON.stringify(loginInfo);
    user.login(loginInfo).then(function(users) {
        $scope.users = users.data;
    }, function(status) {});
};

MVC Controller

public string LogIn(string loginInfo) {
  
  var obj = new JavaScriptSerializer();
  var result = obj.DeserializeObject(loginInfo);
  
  
  var db = new comaxDataEntities();
  var linq = db.accounts.Where(u => u.userName == loginInfo);
  var useraccount = linq.FirstOrDefault < account > ();
  
  var javaScriptSerializer = new JavaScriptSerializer();
  string jsonString = javaScriptSerializer.Serialize(useraccount);
  return jsonString;
  
}

Solution

  • You service should pass stringify data to the server, as you are declared parameter as string on action like JSON.stringify({loginInfo: loginInfo})

    CODE

    $http({
        url: './data/LogIn',
        method: "POST",
        data: JSON.stringify({
            loginInfo: loginInfo
        }),
        headers: {
            'Content-Type': 'application/json'
        }
    }).success(function(data, status, headers, config) {
        $scope.users = data.users;
    }).error(function(data, status, headers, config) {
        $scope.status = status + ' ' + headers;
    });
    

    For more better way i would prefer to create loginInfo class on server side, that would directly gets mapped to class, you will not need to de-serialize it.