简体   繁体   English

如何将JSON数据从C#控制器传递到angular js?

[英]How to pass json data from C# controller to angular js?

How to pass json data from C# controller to angular js ? 如何将JSON数据从C#控制器传递到angular js? I want to pass json from controller to angular js. 我想将json从控制器传递到有角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 C#控制器代码

 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 但无法在angular js控制器中获取以下数据是控制台中引发的错误,“错误:JSON.parse:预期属性名称或'}'在JSON数据的第1行第2列

how to fix this? 如何解决这个问题? Whats the problem here? 这里有什么问题?

I suspect it is because the format of your JSON. 我怀疑是因为您的JSON格式。 You are using single quotes vs double. 您使用的是单引号还是双引号。 Valid JSON uses double quotes . 有效的JSON使用双引号

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. 这是我运行您的json时得到的信息,我已将响应更改为HttpResponseMessage并明确设置了响应内容类型以消除此问题。 Based on your error being on Javascript side i think your problem is your single quotes in your JSON. 基于您在Java脚本方面的错误,我认为您的问题是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: 结果是:

破灭

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: 正常工作:

正确

use EF to create json object and use web api controller to GET(select),PUT(update),POST(insert),DELETE(delete) data 使用EF创建json对象并使用Web api控制器获取(选择),放置(更新),发布(插入),删除(删除)数据

 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;
        }
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM