Currently, I am working on developing an application using AngularJS. In this project, I need to populate the customer list using data from a database. To achieve this, I have written a web method to retrieve the necessary data:
[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);
}
}
public class CustName
{
public string cust_F_name { get; set; }
}
To fetch the JSON data, use the following code:
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
});
});
To display the data, use the following HTML:
<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>
Currently, the output I am receiving is:
However, I would like to access the data in JSON format in name-value pairs. I'm unsure how to accomplish this and would appreciate any guidance you can provide. Thank you in advance.