Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

How to pass json data from C# controller to angular js ? I want to pass json from controller to angular js. I tried different but none of them worked. See my code below,

var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http) {
    $http.get("/adnActions/getJson")
    .success(function (response) { alert(response.records); $scope.names = response.records; });
});

C# controller code

 public async Task<string> getJson()
    {
                 data="{'records':[ {'Name':'Alfreds Futterkiste','City':'Berlin','Country':'Germany'}, {'Name':'Ana Trujillo Emparedados y helados','City':'México D.F.','Country':'Mexico'}]}";
       return data;    

    }

but am unable to get the data in angular js controller below is the error raised in console, "Error: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data

how to fix this? Whats the problem here?

share|improve this question
1  
I wonder if, since your method is marked async but you're not awaiting, if the object being serialized is the Task<string>.ToString() rather than your intended JSON payload. Can you do a network capture and see what the actual response from your service is at the browser? This might reveal the problem. – Erik Noren Jul 6 '15 at 15:45
    
Guessing here, but what content type does your API return? Does it need to be application/json for Angular to pick it up? – LukeP Jul 6 '15 at 15:45
    
It should be Json format so that i can give that returned value to my angular variable. ($scope.names) – Kavitha Jul 6 '15 at 16:39
up vote 1 down vote accepted

I suspect it is because the format of your JSON. You are using single quotes vs double. Valid JSON uses double quotes.

Here is what i get when i run your json i have changed the response to be HttpResponseMessage and explicitly set the response content type to eliminate this as an issue. Based on your error being on Javascript side i think your problem is your single quotes in your JSON.

    public async Task<HttpResponseMessage> GetJsonSingle()
    {
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent("{'records':[ {'Name':'Alfreds Futterkiste','City':'Berlin','Country':'Germany'}, {'Name':'Ana Trujillo Emparedados y helados','City':'México D.F.','Country':'Mexico'}]}")
        };

        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        return result;
        }

results in:

busted

While double quotes:

     public async Task<HttpResponseMessage> GetJsonDouble()
    {
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent("{\"records\":[ {\"Name\":\"Alfreds Futterkiste\",\"City\":\"Berlin\",\"Country\":\"Germany\"}, {\"Name\":\"Ana Trujillo Emparedados y helados\",\"City\":\"México D.F.\",\"Country\":\"Mexico\"}]}")
        };

        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        return result;
    }

works correctly:

correct

share|improve this answer

use EF to create json object and use web api controller to GET(select),PUT(update),POST(insert),DELETE(delete) data

 public class CarsController : ApiController
    {
        private static readonly ICarRepository _cars = new CarRepository();
        // GET api/<controller>
        public IEnumerable<Car> Get()
        {
            return _cars.GetAllCars();
        }

        // GET api/<controller>/5
        public Car Get(int id)
        {
            Car c = _cars.GetCar(id);
            if (c == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);
            return c;
        }

        // POST api/<controller>
        public Car Post(Car car)
        {
            return _cars.AddCar(car);
        }

        // PUT api/<controller>/5
        public Car Put(Car car)
        {
            if (!_cars.Update(car))
                throw new HttpResponseException(HttpStatusCode.NotFound);
            return car;
        }

        // DELETE api/<controller>/5
        public Car Delete(int id)
        {
            Car c = _cars.GetCar(id);
            _cars.Remove(id);
            return c;
        }
    } 
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.