如何在c#中收集JSON,这篇文章来自angularjs

本文关键字:文章 angularjs JSON | 更新日期: 2023-09-27 17:50:06

我是一个基本的开发人员,我只需要在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文件中收集数据。谁能告诉我怎么做?

如何在c#中收集JSON,这篇文章来自angularjs

你也可以试试下面的代码:创建服务。

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

在你的控制器中:以这种方式注入你的Service来实现它的方法/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) {
}
}]);

你应该创建一个服务来发送数据到你的控制器。您需要以下内容:

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

在你的angular控制器中,只需调用服务WorkingService.saveData($scope.form)

你可以在你的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方法。