8

我使用 Web API 创建了 MVC 4.0 应用程序,该应用程序以 JSON 格式返回数据(我正在使用 NewtonSoft.Json 将对象序列化为 json)并尝试在 ng-Grid 中绑定数据。我正在接收以下格式的数据:

"[{\"Name\":\"FIRST_NAME\",\"Value\":\"FIRST_NAME\"},{\"Name\":\"CURRENT_DATE_TIME\",\"Value\":\"CURRENT_DATE_TIME\"},{\"Name\":\"CLIENTID\",\"Value\":\"CLIENTID\"},{\"Name\":\"CALLMODE\",\"Value\":\"CALLMODE\"}, {\"Name\":\"new 321\",\"Value\":null}]"

当我尝试将相同分配给数据时:ng-Grid 的每个字符都填充在不同的行上。以下是我写的javascript:

var guidesRespApp = angular.module('guidesRespApp', ['ngGrid']);

//Get Data from restful API.
guidesRespApp.controller('MyCtrl', function ($scope, $http) {
    $http.get('/api/datadictionary').success(function (thisdata) {
            $scope.myData  =  thisdata;
    });

     $scope.filterOptions = {
        filterText: '',
        useExternalFilter: true,
    };


    //Setting grid options
    $scope.gridOptions = {
      data: 'myData',
      multiSelect: true,
      filterOptions: { filterText: '', useExternalFilter: false },
      enableRowReordering: false,
      showGroupPanel: false,
      maintainColumnRatios: false,
      groups: [],
      showSelectionCheckbox: true,
      showFooter: true,
      enableColumnResize: true,
      enableColumnReordering: true
    };


//    $scope.totalFilteredItemsLength = function() {
//        //return self.filteredRows.length;
//        };

});

如果像下面这样手动分配,数据将显示在网格中:

$scope.myData = [{"Name":"FIRST_NAME","Value":"FIRST_NAME"},{"Name":"CURRENT_DATE_TIME","Value":"CURRENT_DATE_TIME"},{"Name":"CLIENTID","Value":"CLIENTID"},{"Name":"CALLMODE","Value":"CALLMODE"}];

谁能帮我理解如何解决它?当我在 filtertext 中键入值时,我还想显示过滤项目的计数。

4

2 回答 2

10

http://angular-ui.github.io/ng-grid/中所述,网格中显示的数据是数组类型,并且该数组中的每个元素都映射到正在显示的行。所以我修改了我的代码,如下所示,它对我有用:

$http.get('http://localhost:12143/api/datadictionary').success(function (thisdata) {
    //Convert data to array.
    var myData =  $.parseJSON(JSON.parse(thisdata));
    $scope.myData  =  myData; 
});

甚至var myData = $.parseJSON(angular.fromJson(thisdata));还在工作。只是我们需要首先解析数据(为此我使用JSON.parse())然后转换为数组(为此我使用$.parseJSON())。

于 2013-05-01T14:22:02.697 回答
3

尝试将 get 回调更改为以下之一:

$http.get('/api/datadictionary').success(function (thisdata) {
        $scope.myData  =  JSON.parse(thisdata);
        // or
        $scope.myData = angular.fromJson(thisdata);
});

关于 webapi 如何返回 json,请参考此内容。 ASP.NET WebAPI:如何控制返回给客户端的字符串内容?

于 2013-04-30T22:45:43.810 回答