【问题标题】:how to customised Json field dynamically如何动态自定义 Json 字段
【发布时间】:2016-02-24 09:30:59
【问题描述】:
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>  
    <script>

            angular.module("myapp", []).controller("MyController", function ($scope, $http) {
                //$scope.retData = {};
                //$scope.retData.getResult = function (item, event) {
                    $http.post('Sample.aspx/GetEmployees', { data: {} }).success(function (data, status, headers, config) {
                        debugger
                        $scope.retData = data.d;
                        var nik = data.d;
                    })
                .error(function (data, status, headers, config) {
                    $scope.status = status;
                });
                //}
            }).config(function ($httpProvider) {
                $httpProvider.defaults.headers.post = {};
                $httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";
            });  
    </script>  



 <body ng-app="myapp"> 
     <div ng-controller="MyController">
        <p>Looping with objects:</p>
        <ul>
          <li ng-repeat="x in retData">
            {{ x.Education + ', ' + x.UserName }}
          </li>
        </ul>

        </div>
</body>  

"[{"UserId":1,"UserName":"Suresh","Education":"B.Tech","Location":"Chennai","Item":1,"Quantity":2},{"UserId":2,"UserName":"Rohini","Education":"M.Sc. ","Location":"Chennai","Item":5,"Quantity":8},{"UserId":3,"UserName":"Praveen ","Education":"B.Tech","Location":"Guntur","Item":12,"Quantity":7},{"UserId":4,"UserName":"Lal","Education":"M.Sc. ","Location":"Agra","Item":44,"Quantity":7},{"UserId":5,"UserName":"Puneet","Education":"B.Sc.","Location":"Gurgaon","Item":9,"Quantity":9},{"UserId":6,"UserName":"Rohit","Education":"BCA","Location":"Delhi","Item":76,"Quantity":90}]

下面是带有数据库脚本的 Webmethod 代码。请为我提供此参考代码的解决方案。这是一种动态的 Json 字符串。

[WebMethod]
 public static string GetEmployees()
 {
   string query = "[GetCustomers_Pager]";
   SqlCommand cmd = new SqlCommand("select * from userdetails");
   return DataTableToJSONWithJavaScriptSerializer(GetData(cmd).Tables[0]);
 }

    private static DataSet GetData(SqlCommand cmd)
    {
        string strConnString = ConfigurationManager.ConnectionStrings["testConnectionString"].ToString();
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds, "Customers");
                    return ds;
                }
            }
        }
    }

    public static string DataTableToJSONWithJavaScriptSerializer(DataTable table)
    {
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
        Dictionary<string, object> childRow;
        foreach (DataRow row in table.Rows)
        {
            childRow = new Dictionary<string, object>();
            foreach (DataColumn col in table.Columns)
            {
                childRow.Add(col.ColumnName, row[col]);
            }
            parentRow.Add(childRow);
        }
        return jsSerializer.Serialize(parentRow);
    }

这是一种节省您时间的数据库脚本。

CREATE TABLE [dbo].[userdetails](
    [UserId] [int] NULL,
    [UserName] [varchar](50) NULL,
    [Education] [varchar](50) NULL,
    [Location] [varchar](50) NULL,
    [Item] [int] NULL,
    [Quantity] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[userdetails] ([UserId], [UserName], [Education], [Location], [Item], [Quantity]) VALUES (1, N'Suresh', N'B.Tech', N'Chennai', 1, 2)
INSERT [dbo].[userdetails] ([UserId], [UserName], [Education], [Location], [Item], [Quantity]) VALUES (2, N'Rohini', N'M.Sc. ', N'Chennai', 5, 8)
INSERT [dbo].[userdetails] ([UserId], [UserName], [Education], [Location], [Item], [Quantity]) VALUES (3, N'Praveen ', N'B.Tech', N'Guntur', 12, 7)
INSERT [dbo].[userdetails] ([UserId], [UserName], [Education], [Location], [Item], [Quantity]) VALUES (4, N'Lal', N'M.Sc. ', N'Agra', 44, 7)
INSERT [dbo].[userdetails] ([UserId], [UserName], [Education], [Location], [Item], [Quantity]) VALUES (5, N'Puneet', N'B.Sc.', N'Gurgaon', 9, 9)
INSERT [dbo].[userdetails] ([UserId], [UserName], [Education], [Location], [Item], [Quantity]) VALUES (6, N'Rohit', N'BCA', N'Delhi', 76, 90)

【问题讨论】:

  • 欢迎来到 StackOverflow!你的第一个错误是你发布了很多代码,但没有解释它的作用、它的错误之处以及你想要它做什么。
  • 这里我只想绑定 li 列表中的 Education 和 UserName。

标签: angularjs json


【解决方案1】:

尝试 $http.get 而不是 post(假设您只想检索数据)

$http.get("Sample.aspx/GetEmployees")
    .then(function(response) {
        //First function handles success
        $scope.retData = response.data;
    }, function(response) {
        //Second function handles error
        $scope.status = "Something went wrong";
    });

【讨论】:

  • 在浏览器中使用调试器时,这里的数据显示在 $scope.retData 中,但我想在 li 中绑定它。并且使用 get 方法它仍然没有绑定。
  • 检查this link,它正在工作。不确定您使用的角度版本
  • 我完全同意你的看法。这件事从我的角度来说已经奏效了。我正在尝试一些新的东西。以上是我的代码,我正在为您提供 Json 代码 wid 数据库脚本。
  • 我的问题不清楚。检查您是否从后端获得正确的 json 对象。我假设您在问题区域中提到了 json 对象。
  • 谢绝任何人帮助我
猜你喜欢
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 1970-01-01
  • 2020-04-18
  • 2021-12-05
  • 1970-01-01
  • 2020-06-06
  • 2021-08-19
相关资源
最近更新 更多