FrenkyB
FrenkyB

Reputation: 7207

Angular response appends object at the end

This is my POST request:

$scope.TestPost = function (par1, par2) {

                $http.post('EmployeeService.asmx/GetAllEmployees',
                    {                    
                        par1: par1,
                        par2: par2       
                })
                .then(function (response) {
                    $scope.employees = response.data;
                })
            };

And this is code that gets called on the server side. Code is called correctly and json serialized object is written to response:

[WebMethod]
public void GetAllEmployees(string par1, string par2)
{
    List<Employee> listEmployees = new List<Employee>();
    string cs = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
    using(SqlConnection con = new SqlConnection(cs))
    {
        List<Employee> _list = new List<Employee>();
        SqlCommand cmd = new SqlCommand("SELECT * FROM tblEmployees", con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        while(rdr.Read())
        {
            Employee emp = new Employee
            {
                id = Convert.ToInt32(rdr["Id"]),
                name = rdr["Name"].ToString(),
                gender = rdr["Gender"].ToString(),
                salary = Convert.ToInt32(rdr["Salary"])
            };
            listEmployees.Add(emp);
        }
    }

    JavaScriptSerializer js = new JavaScriptSerializer();            
    Context.Response.Write(js.Serialize(listEmployees));
}

Response object is this - some strange line is appended at the end {"d":null} which I can not understand why. I am also receiving error on the client side: SyntaxError: Unexpected token:

"[{"id":1,"name":"Ben","gender":"Male","salary":55000},
{"id":2,"name":"Sara","gender":"Female","salary":68000},
{"id":3,"name":"Mark","gender":"Male","salary":57000},
{"id":4,"name":"Pam","gender":"Female","salary":53000},
{"id":5,"name":"Todd","gender":"Male","salary":60000}]{"d":null}"

Upvotes: 1

Views: 403

Answers (1)

FrenkyB
FrenkyB

Reputation: 7207

Thanks to @82Tuskers and this post: Differences between Response.End() and Response.Flush()

I've found the solution. I've changed code at the end of server side function to:

Context.Response.Clear();
Context.Response.Write(js.Serialize(listEmployees));
Context.Response.Flush();
Context.Response.End(); 

Response is now OK.

Upvotes: 1

Related Questions