Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度数据绑定不工作_Javascript_C#_Asp.net_Json_Angularjs - Fatal编程技术网

Javascript 角度数据绑定不工作

Javascript 角度数据绑定不工作,javascript,c#,asp.net,json,angularjs,Javascript,C#,Asp.net,Json,Angularjs,我一直在使用AngularJs处理ASP.NET webforms中的数据绑定 我有以下几点: (function () { var app = angular.module("registrationModule", []); app.factory("exampleService", exampleService); function exampleService($http) { function getData

我一直在使用AngularJs处理ASP.NET webforms中的数据绑定

我有以下几点:

 (function () {
        var app = angular.module("registrationModule", []);

        app.factory("exampleService", exampleService);

        function exampleService($http) {
            function getData(id) {
                return $http.post("LegacyPage.aspx/GetData", { id: id })
                .then(function (response) {
                    return response.data; //data comes back as json
                   //Also tried response.data.d
                });
            };

            return {
                getData: getData
            };
        };

        app.controller("MainCtrl", ["$scope", "exampleService", MainCtrl]);

        function MainCtrl($scope, exampleService) {

            $scope.generateText = "Generate";
            $scope.loading = false;


            function onComplete(data) {
                Unload(data);
            }

            function err(reason) {
                Unload("Ajax has failed.");
            }

            $scope.GetData = function (id) {
                Load();
                exampleService.getData(id).then(onComplete, err);
            }

            function Unload(result) {
                $scope.loading = false;
                $scope.generating = false;
                $scope.generateText = "Generate";
                $scope.theData = result; //does not work

                //I have tried (with no success):

                //$scope.$apply(function () {
                //$scope.theData = result;
                //});

                //$scope.theData = JSON.parse(result);

                //$scope.theData = angular.fromJson(result);
            }

            function Load() {
                $scope.loading = true;
                $scope.generating = true;
                $scope.generateText = "Generating...";
            }
        };

    }());
我的HTML:

<div ng-app="registrationModule">

    <div ng-controller="MainCtrl">
        <input style="display: block; margin: 0 auto;" type="text" class="form-control" placeholder="ID" ng-model="id" />
        <input ng-click="GetData(id)" type="button" class="btn btn-primary btn-lg" value="{{generateText}}" ng-disabled="generating" />

        <div class="row">
            <div class="span10">
                <table class="table table-responsive table-hover table-condensed">
                    <tr>
                        <th>ID</th>
                        <th>Activity Code</th>
                        <th>Duration</th>
                        <th>Date Created</th>
                    </tr>
                    <tr ng-repeat="element in theData">
                        <td>{{element.ID}}</td>
                        <td>{{element.ActivityCode}}</td>
                        <td>{{element.Duration}}</td>
                        <td>{{element.DateCreated}}</td>
                    </tr>
                </table>
                <br />
            </div>
        </div>
    </div>
</div>

身份证件
活动代码
期间
创建日期
{{element.ID}
{{element.ActivityCode}
{{element.Duration}
{{element.DateCreated}

代码隐藏/后端c#:

[WebMethod]
公共静态字符串GetData(int-id)
{
var dt=获取数据(id);
如果(dt==null)返回“”;
var json=dt.Serialize()??“”;
返回json;
}
公共静态字符串序列化(此DataTable dt)
{
如果(dt==null)
{
抛出新的NullReferenceException(“dt参数不能为null”);
}
尝试
{
var serializer=新的JavaScriptSerializer();
var rows=新列表();
字典行;
foreach(数据行dr在dt.行中)
{
行=新字典();
foreach(dt.列中的数据列列列)
{
行添加(列名称,dr[col]);
}
行。添加(行);
}
返回序列化程序。序列化(行);
}
抓住
{
返回null;
}
}

从本质上讲,数据以JSON的形式返回,但没有成功绑定。我正在用angular返回JSON,但我无法处理它。我想我只是缺少了一些非常简单的东西,但还没有找到解决方案

您没有将
响应.data
绑定到任何变量。您需要添加一个
$scope.theData=response.data在控制器中

[编辑:更正,被您的代码弄糊涂了。将控制器更改为:

$scope.theData=结果
$scope.theData=result.data

至于你的服务,去掉
。然后(…)
,因为它什么都不做

        function getData(studentId) {
            return $http.post("LegacyPage.aspx/GetData", { id: id });
        };
除非您打算更改响应,否则在这种情况下,您需要添加一个
返回值

        function getData(studentId) {
            return $http.post("LegacyPage.aspx/GetData", { id: id })
            .then(function (response) {
                return response.data;
            });
        };
至于标准,我建议使用
.catch(err)
,因为这样可以链接多个
.then(…)
语句,并且仍然使用单个错误处理程序。它也更容易阅读

exampleService.getData(id).then(onComplete).catch(err);

我想我可能发现了你的问题。在getData()函数中,您将id参数命名为“studentId”,但稍后将其称为“id”。以下是修复方法:

function getData(studentId) {
    return $http.post("LegacyPage.aspx/GetData", {
        id: studentId // This used to be "id", but needed to be "studentId"
    })
    .then(function (response) {
        return response.data;
    });
};
编辑

听起来您的问题可能是API返回了一个散列对象,如下所示:

$scope.theData = {
    ID: 1,
    ActivityCode: 'foo'
    ...etc
}
如果是这种情况,则不需要使用ng repeat指令来显示一个对象。您只需更改您的视图,如下所示:

<div ng-app="registrationModule">

    <div ng-controller="MainCtrl">
        <input style="display: block; margin: 0 auto;" type="text" class="form-control" placeholder="ID" ng-model="id" />
        <input ng-click="GetData(id)" type="button" class="btn btn-primary btn-lg" value="{{generateText}}" ng-disabled="generating" />

        <div class="row">
            <div class="span10">
                <table class="table table-responsive table-hover table-condensed">
                    <tr>
                        <th>ID</th>
                        <th>Activity Code</th>
                        <th>Duration</th>
                        <th>Date Created</th>
                    </tr>
                    <tr>
                        <td>{{theData.ID}}</td>
                        <td>{{theData.ActivityCode}}</td>
                        <td>{{theData.Duration}}</td>
                        <td>{{theData.DateCreated}}</td>
                    </tr>
                </table>
                <br />
            </div>
        </div>
    </div>
</div>

所以我想出来了。问题是ng repeat无法绑定数据。这是因为数据以字符串的形式返回。所以每个对象的每个属性都是一个字符串,angular显然不喜欢这样。我所需要做的就是将后端代码更改为:

 [WebMethod]
public static List<ReportData> GetData(int id)
{
    var dt = GetData(id);

    if (dt == null) return dt;

    var reportElements = dt.ToObjectList<ReportData>();

    //var json = dt.Serialize() ?? "";

    return reportElements;
}

public class ReportData
{
    public int Id { get; set; }
    public string ActivityCode { get; set; }
    public string Duration { get; set; }
    public DateTime DateCreated { get; set; }
}

public static List<T> ToObjectList<T>(this DataTable table) where T : class, new()
{
    try
    {
        var list = new List<T>();

        foreach (var row in table.AsEnumerable())
        {
            T obj = new T();

            foreach (var prop in obj.GetType().GetProperties())
            {
                try
                {
                    PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                    propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                }
                catch
                {
                    continue;
                }
            }

            list.Add(obj);
        }

        return list;
    }
    catch
    {
        return null;
    }
}
在我的卸载功能中:

 $scope.theData = result;

是的,很抱歉搞混了,我还遗漏了一份退货声明。我已经编辑了问题中的
exampleService
。还尝试了
.data.d
@user3574076仍不工作。。。?在这一点上应该是这样的。尝试在您的服务中填充
[“$http”,exampleService]
。@user3574076如果仍然不起作用,请使用
console.log(响应)
部分查看Google Chrome>控制台(F12)中的输出。如果看起来不错,请在Unload语句中执行
console.log(result)
,查看那里输出的内容。像这样测试你的链,看看它在哪里断了。@ngDeveloper现在测试它,会让你知道outcome@user3574076可能后端服务器返回的json无效,或者它没有将头mime类型设置为application/json,因此Angular将其视为字符串。您可以尝试类似
console.log(JSON.parse(result))在控制器中
卸载()
。请注意,JSON.parse(…)仅适用于现代浏览器。抱歉,代码只是一个示例,它实际上是我真实代码中的id。现在的问题是ng-repeat@user3574076别担心。在范围上设置响应后,能否确认$scope.theData是一个数组?试着在设置后立即执行一个console.log($scope.theData)。看看我的答案,我发现了太棒了,很高兴你发现了!)
 [WebMethod]
public static List<ReportData> GetData(int id)
{
    var dt = GetData(id);

    if (dt == null) return dt;

    var reportElements = dt.ToObjectList<ReportData>();

    //var json = dt.Serialize() ?? "";

    return reportElements;
}

public class ReportData
{
    public int Id { get; set; }
    public string ActivityCode { get; set; }
    public string Duration { get; set; }
    public DateTime DateCreated { get; set; }
}

public static List<T> ToObjectList<T>(this DataTable table) where T : class, new()
{
    try
    {
        var list = new List<T>();

        foreach (var row in table.AsEnumerable())
        {
            T obj = new T();

            foreach (var prop in obj.GetType().GetProperties())
            {
                try
                {
                    PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                    propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                }
                catch
                {
                    continue;
                }
            }

            list.Add(obj);
        }

        return list;
    }
    catch
    {
        return null;
    }
}
     function exampleService($http) {
        function getData(id) {
            return $http.post("LegacyPage.aspx/GetData", { id: id })
            .then(function (response) {
                return response.data; //data comes back as json
               //Also tried response.data.d
            });
        };

        return {
            getData: getData
        };
    };
 $scope.theData = result;