Ibrahim Shaikh Ibrahim Shaikh - 2 months ago 18
ASP.NET (C#) Question

return json data from web service

[WebMethod]
public void contacters()
{
SqlConnection con = new SqlConnection(ConnectionString);
List<object> obj = new List<object>();
SqlCommand cmd = new SqlCommand("select * from authors", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for(int i=0; i<ds.Tables[0].Rows.Count; i++)

{
obj.Add(ds.Tables[0].Rows[i][0]);
obj.Add(ds.Tables[0].Rows[i][1]);
obj.Add(ds.Tables[0].Rows[i][2]);
}
JavaScriptSerializer ser = new JavaScriptSerializer();
var json = ser.Serialize(obj);
Context.Response.Write("{"+'"'+"info"+'"'+";"+json+"}");
}


This Is my Web service

And My JS File

var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http) {
$http.post("WebService2.asmx/contacters")
.then(function (response) {
$scope.names = response.data.info;
console.log(response.data.info);
});
});


My Code On ASPX
testjson.aspx


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">


<div ng-app="myApp" ng-controller="customersCtrl">

<table>
<tr ng-repeat="x in names">
<td>{{ x.AuthorId }}</td>
<td>{{ x.Fname }}</td>
<td>{{ x.Lname }}</td>
</tr>
</table>

</div>
<script type="text/javascript" src="testjavascript.js"></script>

</asp:Content>


webservice is displaying data when i debug webservice,

But the problem is when i run the page
testjson.aspx
data is not displaying


Can anybody help me out on this


web service is running fine, I think there may be a


problem in my JS file

Answer

Try this:

public class ContactModel
{
    public int AuthorId { get; set; }
    public string Fname { get; set; }
    public string Lname { get; set; }
}

[WebMethod]
public void contacters()
{
    SqlConnection con = new SqlConnection(ConnectionString);
    List<ContactModel> obj = new List<ContactModel>();
    SqlCommand cmd = new SqlCommand("select * from authors", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        obj.Add(new ContactModel
                    {
                    AuthorId = (int) ds.Tables[0].Rows[i][0],
                    Fname = (string) ds.Tables[0].Rows[i][1],
                    Lname = (string) ds.Tables[0].Rows[i][2]
                    });
    }
    JavaScriptSerializer ser = new JavaScriptSerializer();
    var returnModel = new { info = obj };
    var json = ser.Serialize(returnModel);
    Context.Response.Write(json);
}