Pooria.Shariatzadeh
Pooria.Shariatzadeh

Reputation: 301

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

Upvotes: 1

Views: 1854

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

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.

Upvotes: 2

Rabi
Rabi

Reputation: 2220

Make the following changes -

C#

create a new class -

public class LoginInformation
{
   public string user { get; set;}
   public string password { get; set; }
}

change the parameter of LogIn method to use the new class

public string LogIn(LoginInformation loginInfo)
{
}

Angular

remove this line from controller (since you have mentioned headers: {'Content-Type': 'application/json'})

loginInfo = JSON.stringify(loginInfo);

make sure the URL (url: './data/LogIn',) is a valid one.

Upvotes: 0

Related Questions