Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass value from Angular controller to C# API

Tags:

c#

sql

angularjs

I currently have a C# controller with a method AddOne():

public void AddOne(int num)
    {
        using (cnxn)
        {
            using (SqlCommand sc = new SqlCommand("INSERT INTO Employees VALUES('this','works'," + num +")", cnxn))
            {
                cnxn.Open();
                sc.ExecuteNonQuery();
                cnxn.Close();
            }
        }
    }

And then for my Angular code, I have a controller EntriesController:

var EntriesController = function ($scope, $stateParams, $location, $http) {
    $scope.Entries = {
        num: 10
    };

    $scope.addValues = function () {

        $http.post('Data/addOne', { num });
    }

}

EntriesController.$inject = ['$scope', '$stateParams', '$location', '$http'];

I have the EntriesController's addValues() function registered to a button on a view which does send insert values into my database if I hardcode them like this:

AddOne:

public void AddOne()
{
    using (cnxn)
    {
        using (SqlCommand sc = new SqlCommand("INSERT INTO Employees VALUES('this','works',10)", cnxn))
        {
             cnxn.Open();
             sc.ExecuteNonQuery();
             cnxn.Close();
        }
    }
}

and the addValues():

$scope.addValues = function () {

    $http.post('Data/addOne');
}

How can I pass data from my Angular's post to my C#'s controller? Thanks, everyone!

like image 667
WakaChewbacca Avatar asked Sep 20 '26 09:09

WakaChewbacca


1 Answers

I was quite the fool. I needed to pass $scope.Entries with $http.post() and then name the parameters in my C# controller's AddOne() method accordingly. Ex: For the following Angular Controller:

var EntriesController = function ($scope, $stateParams, $location, $http) {
    $scope.Entries = {
        firstName: '',
        lastName: '',
        num: 12
    };
    $scope.addValues = function () {
        $http.post('/Data/addOne', $scope.Entries)

    };
}

My C# controller's AddOne() method to process the post:

 public void AddOne(string firstName, string lastName, int num)
 {
      using (cnxn)
      {
          using (SqlCommand sc = new SqlCommand("INSERT INTO TableName VALUES('"+ firstName +"','"+ lastName +"',"+num+")", cnxn))
          {
              cnxn.Open();
              sc.ExecuteNonQuery();
              cnxn.Close();
          }
      }
 }

Woot.

like image 126
WakaChewbacca Avatar answered Sep 22 '26 23:09

WakaChewbacca