Trying to learn Angularjs by building on a working example The original example displayed a simple string on the button click. I am trying to modify to display a table of data returned from a C# WebMethod
My WebMethod seenms to be OK - I can step into it and a JSON string is returned like:
[
{"Code":"Code1","Desc":"Code1 Desc"},
{"Code":"Code2","Desc":"Code2 Desc"},
....
]
Any help would be appreciated
Thanks
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test1.aspx.cs" Inherits="SampleAngularjs.Test1" %>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<body ng-app="codeapp">
<div ng-controller="CodeController" >
<button ng-click="myData.doClick(item, $event)">Send AJAX Request</button>
<br/>
<table>
<tr>
<th>Code</th>
<th>Desc</th>
</tr>
<tr ng-repeat="code in myData.codes">
<td>{{code.Code}}</td>
<td>{{code.Desc}}</td>
</tr>
</table>
</div>
<script>
angular.module("codeapp", [])
.controller("CodeController", function ($scope, $http) {
$scope.myData = {};
$scope.myData.codes = [];
$scope.myData.doClick = function (item, event) {
$http.post('Test1.aspx/GetAllCodes', { data: {} })
.success(function (data, status, headers, config) {
//$scope.myData.fromServer = data.d;
$scope.myData.codes = data;
})
.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>
</html>
[WebMethod]
public static string GetAllCodes()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(@"Data Source=SQL2012;Initial Catalog=XXX;Persist Security Info=True;Password=xxxx;User ID=xxxx"))
{
using (SqlCommand cmd = new SqlCommand( "SELECT Code=TheCode, [Desc]=TheDescription FROM Codes ", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
serializer.MaxJsonLength = 50000000;
string sJson = serializer.Serialize(rows);
return (sJson);
}
I did some more testing If I create a list manually to look like my Json list back from db - I can display the manually built list but not the one generated from the Json gotten from server
Here is screenshot