如何从angularjs发布的c#中收集JSON?

时间:2015-05-21 07:02:11

标签: c# json angularjs

我是一名基础开发人员,我只需要在c#文件中收集以下JSON数据:

{
  "text":"This is a message !!!",
  "userid":"some_id",
  "username":"username",
  "fname":"some_name",
  "lname":"some_surname",
  "iurl":"url_here",
  "type":"some_type"
}

使用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);
    }
}]);

如上所述,showValues会返回数组。

现在我只想在ValuesController.cs文件中收集数据。谁能建议怎么做?

3 个答案:

答案 0 :(得分:1)

您也可以尝试以下代码: 创建服务。

 app.service("angularService", function ($http) {
     this.AddValues= function (showValues) {
            var response = $http({
                method: "post",
                url: "api/values/YourmethodName",
                data: showValues
            });
            return response;
        }
    });

在您的控制器中:以这种方式在此处注入您的服务以实现其方法/服务

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) {
}
}]);

答案 1 :(得分:0)

您应该创建一个将数据发送到控制器的服务。你需要这些东西:

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

在角度控制器中,只需拨打服务WorkingService.saveData($scope.form)

答案 2 :(得分:0)

您可以在Angular控制器中使用此代码调用MVC控制器(ValuesController.cs):

$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..");
});

最好将ajax请求放在工厂服务中,并从控制器中调用服务中的http方法