Reputation: 97
I'm trying to display data from sql database. First I converted my data to JSON object in my UserService.asmx.cs file.
public string GetUserDetails()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("select UserID=id,Name=username,Mail=Email from users", 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);
}
return serializer.Serialize(rows);
}
}
}
then I tried to fetch the JSON object using AngularJS controller script.js
$scope.getUser = function () {
$.ajax({
type: "POST",
url: "UserService.asmx/GetUserDetails",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = $.parseJSON(data.d);
$.each(parsed, function (i, jsondata) {
$("#showdata").append("ID: " + jsondata.UserID + "<br/>" + "Username: " + jsondata.Name);
});
},
error: function (XHR, errStatus, errorThrown) {
var err = JSON.parse(XHR.responseText);
errorMessage = err.Message;
alert(errorMessage);
}
});
};
then the data is supposed to show on view on a button click event getUser()
<form id="form1" ng-controller="UserCntrl" ng-submit="save()">
<div>
<p>Username: </p>
<input id="Text1" type="text" placeholder="Select Username" ng-model="Username" />
<p>Email: </p>
<input id="Text2" type="email" placeholder="Email Address" ng-model="Email" />
<p>Password: </p>
<input id="Text3" type="password" placeholder="Provide Password" ng-model="Password" />
<br /><br /><br />
<input id="Button1" type="submit" value="Register" />
</div>
<div>
<input type="button" id="btnFetch" value="Fetch" ng-click="getUser()" />
</div>
<div id="showdata">
<table>
<tr>
<td>UserID</td>
<td>Username</td>
<td>Email</td>
</tr>
<tr>
<td>{{IId}}</td>
<td>{{Username}}</td>
<td>{{Email}}</td>
</tr>
</table>
</div>
</form>
but when I click the button no data is being shown. If anyone point me out to the right direction that would be much appreciated.
Upvotes: 0
Views: 13104
Reputation: 653
I Think you might forgot about [WebMethod] attribute for your .Net method
Upvotes: 1