Reputation: 444
I'm a basic developer, I just need to collect the following JSON data in a c# file:
{
"text":"This is a message !!!",
"userid":"some_id",
"username":"username",
"fname":"some_name",
"lname":"some_surname",
"iurl":"url_here",
"type":"some_type"
}
The above array is posted using angularjs.
app.js:
var app = angular.module('myApp');
app.controller('WorkingCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.form = {};
$scope.post = [];
$scope.submitForm = function () {
$scope.post.text = $scope.form.text;
if ($scope.post.text != '') {
$scope.post.unshift($scope.post.text);
$scope.post.text = '';
}
$scope.remItem = function ($index) {
$scope.post.splice($index , -1);
}
$scope.form.userid = "some_id";
$scope.form.username = "username";
$scope.form.fname = "some_name";
$scope.form.lname = "some_surname";
$scope.form.iurl = "url_here";
$scope.form.type = "some_type";
$scope.showValues = JSON.stringify($scope.form);
}
}]);
As clearly seen above showValues
returns the array.
Now I just wanted to collect data in my ValuesController.cs file. Can anyone suggest how to do that ?
Upvotes: 0
Views: 260
Reputation: 133
You can make call to your MVC controller (ValuesController.cs) using this code in your Angular controller:
$http({
method: 'POST',
url: '/Values/TestMethod',
data: $scope.showValues,
headers: { 'content-type': 'application/json' }
}).
success(function (data) {
//do some operations with the return data if the MVC controller returns data
}).
error(function () {
alert("Error has happened..");
});
It is better to put the ajax request in a factory service and from your controller to call the http method from the service
Upvotes: 0
Reputation: 1119
You could also try this code: Create a service.
app.service("angularService", function ($http) {
this.AddValues= function (showValues) {
var response = $http({
method: "post",
url: "api/values/YourmethodName",
data: showValues
});
return response;
}
});
In your controller: Inject your Service here in this way to implement its method/service
app.controller('WorkingCtrl', ['$scope','angularService',function ($scope, angularService) {
$scope.submitForm = function () {
$scope.form = {};
$scope.form.userid = "some_id";
$scope.form.username = "username";
$scope.form.fname = "some_name";
$scope.form.lname = "some_surname";
$scope.form.iurl = "url_here";
$scope.form.type = "some_type";
$scope.showValues = JSON.stringify($scope.form);
angularService.AddValues(showValues ).then(function (result) {
}
}]);
Upvotes: 1
Reputation: 7476
You should create a service which sends the data to your controller. You need something along these lines:
app.factory('WorkingService', ['$http', '$q', function ($http, $q) {
saveData: function (showValues ) {
var deferred = $q.defer();
$http.post(yourMVCUrl, showValues ).then(function (result) {
deferred.resolve(result);
});
return deferred.promise;
}
}
In your angular controller, just call the service WorkingService.saveData($scope.form)
.
Upvotes: 0