2

I've created an ASP.NET Web API. It seems to be working because I can enter the path into a browser and it displays data from my database tables in what looks like XML format. When I write a jQuery or AngularJS call to GET the data in my MVC website I get errors. After much travail I have discovered that (i think) jQuery or AngularJS want JSON objects, but the Web API must be returning XML objects. I say this because I finally get a success when I call jQuery $.ajax with a dataType: 'xml'. In my Web API I am returning List of my data objects. What is the best or normal way to structure this so that the data matches correctly back to the client AJAX calls?

Steve Gaines
  • 591
  • 1
  • 9
  • 25
  • You should be able to specify an accept header with a value of "application/json" to specifically request JSON. See http://stackoverflow.com/questions/1145588/cannot-properly-set-the-accept-http-header-with-jquery – Tony Hinkle May 05 '16 at 15:29

1 Answers1

0

C#

[WebMethod]
public string GetEmployeeData(int userId)
{
    Dictionary<string, object> returnData = Dictionary<string, object>();

    using(SqlConnection conn = new SqlConnection(connString))
    {
        //etc... etc...
    }

    var jsonSerializer = new JavaScriptSerializer();

    return jsonSerializer.Serialize(returnData);
}

Javascript:

$http.post('MyApp/GetEmployeeData', { userId: 1 }).then(function(response){
    $scope.myData = response.data;
}).catch(function(response) {
    //an error has occurred
});
Kyle
  • 5,407
  • 6
  • 32
  • 47