lightningfire
lightningfire

Reputation: 117

Passing params from AngularJS to C# Controller

I've tried researching this but I can't find anything anywhere that's helpful or any relevant answers.

For my angular controller I have:

app.controller('AdminCtrl', function ($scope, $http) {
$scope.data = {
    Name: '',
    Password: ''
},
$scope.login = function (data) {
    $http({
        method: 'POST',
        url: '/login/postlogin',
        data: JSON.stringify({
            data: $scope.data
        }),
        contentType: "application/json",
        dataType: "json"
    }).success(function (data) {
        alert('success!');
    }).error(function (error) {
        alert(error.message);
    })
}
});

For my c# controller I have a very basic setup:

    [HttpPost]
    public string PostLogin(string data) {          
        return string.Empty;
    }

My issue is that inside of the c# controller, data is always null. Does anyone know how to pass the name and password params over to the c# controller? I know for a fact that I am recieving values for them from my textboxes that I have. I am also recieving the success message/alert.Thanks!

Upvotes: 1

Views: 2871

Answers (2)

trees_are_great
trees_are_great

Reputation: 3911

Data is not a string. In c# make an object with Name and Password as properties and have this:

[HttpPost]
public string PostLogin(Data data) {  

Edit in response to comment: Yes you need to include the namespace that Data is in in your controller. You could try putting the Data object directly above.

 public class Data
    {
        public string Name { get; set; }
        public string Password { get; set; }
    }

For clarity, data should not be stringified, instead just sent as data: data

Upvotes: 3

HaukurHaf
HaukurHaf

Reputation: 13816

Just send $scope.data directly, dont stringify it. Then modify your PostLogin method so it accepts two strings, one called Name and one called Password.

Upvotes: 1

Related Questions