【问题标题】:Unable to bind JSon to list in Angular JS无法将 JSon 绑定到 Angular JS 中的列表
【发布时间】:2014-01-14 10:31:56
【问题描述】:

我正在使用 Angular js 开发一个应用程序,其中我必须使用数据库中的数据填充客户列表,为此我编写了一个 Web 方法来获取类似的数据

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string  getname()
    {
        SqlHelper sql = new SqlHelper();

        DataTable dt = sql.ExecuteSelectCommand("select cust_F_name,cust_L_name from customer");

        Dictionary<string, object> dict = new Dictionary<string, object>();
        object[] arr = new object[dt.Rows.Count];
        List<CustName> custName = new List<CustName>();
        for (int i = 0; i <= dt.Rows.Count - 1; i++)
        {
            CustName c = new CustName();
            c.cust_F_name = dt.Rows[i]["cust_F_name"].ToString();            
            custName.Add(c);

        }
        dict.Add("JsonCustomer", custName);
        JavaScriptSerializer json = new JavaScriptSerializer();
        return json.Serialize(dict);
        //return "Rhsuhikesh";

    }

}
public class  CustName
 {
    public string cust_F_name { get; set; } 
}

将 Json 数据捕获为

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

DemoApp.factory('SimpleFactory', function ($http) {
    return {
        getCustomer: function () {
            return $http.post('Home.aspx/getname', { name: "" });
        }
    };
});

DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
    SimpleFactory.getCustomer().then(function (customer) {
        $scope.Customer = customer.data;
    }, function (error) {
        // error handling
    });
});

并将其视为

<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="DemoApp">
<head runat="server">
    <title></title>
</head>
<body data-ng-controller="SimpleController">
    <form id="form1" runat="server">
    <div>
        Name<input type="text" data-ng-model="Name" />{{ Name }}
        <ul>
            <li data-ng-repeat="customerName in Customer | filter:Name">{{ customerName }} </li>
        </ul>
    </div>
    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="Script/Home.js" type="text/javascript"></script>
</body>
</html>

我得到了 o/p

但我想要它

我必须在名称值对中访问 json 中的数据,但我不明白该怎么做,请帮我解决。

提前致谢。

【问题讨论】:

  • 在我看来,您的响应是 JSON 序列化了两次。

标签: javascript json angularjs c#-4.0


【解决方案1】:

由于您将结果作为 JSON 字符串获取,因此您需要使用 angular.fromJson

将其转换为 JavaScript 对象

例如:

DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
SimpleFactory.getCustomer().then(function (customerData) {
    var customersRawObject = angular.fromJson(customerData);
}, function (error) {
    // error handling
});})

然后你可以这样做:

$scope.customerA=customersRawObject.JsonCustomer[0];

【讨论】:

    猜你喜欢
    • 2015-10-18
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    相关资源
    最近更新 更多