当从MVC

时间:2018-05-11 16:45:12

标签: angularjs json asp.net-mvc http-get jsonresult

我从Restful API获取JSON结果,并确保结果是MVC Controller Method中的JSON,如下所示:

public JsonResult GetApplications()
        {
            string appsRAW;
            HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create("http://apiurl.com/Api/Application/FullDetails");
            GETRequest.Method = "GET";
            GETRequest.Headers.Add("X-ApiKey", "key123");
            String username = "username";
            String password = "password";
            String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
            GETRequest.Headers.Add("Authorization", "Basic " + encoded);
            HttpWebResponse response = GETRequest.GetResponse() as HttpWebResponse;
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                appsRAW=reader.ReadToEnd();            
            }            
            JsonResult applicationsJSON = Json(appsRAW, JsonRequestBehavior.AllowGet);

            return applicationsJSON;
        }

然后我使用以下方法在Angular中调用它:

$scope.applicationList;
    $http.get("/Home/GetApplications").then(function (result) {
        console.log(result);        
    });

然而,在.data的控制台输出中,来自api调用的所有JSON都存在,但存储为长字符串,按字面存储为......

data: "[{"Id":"a2ac8e01-3a5d-4110-8afe-2bde09a4f03b","Firstname":"John","Lastname":"Berry" ... etc. etc.

所以我无法通过result.data.Firstname引用这些值,或者通过申请人对象进行ng-repeat并显示每个字段值。

同样不确定是否重要,在调试和检查C#方法时,.data在每个字段名称和值之前和之后都显示“\”,但是当在浏览器中查看时,它们已经消失了。

我已成功将数组从C#方法发送到角度,并且能够通过.data [0] .data [1]等访问。这是第一次尝试将实际的JSON对象列表发送到MVC的角度。

2 个答案:

答案 0 :(得分:1)

您应该可以对要返回的数据调用JSON.parse,将字符串转回对象。试试这个:

JSON.parse(result.data)

答案 1 :(得分:0)

您可以使用angular.fromJson解析Angular中的JSON字符串。

尝试:

$scope.applicationList;
$http.get("/Home/GetApplications").then(function (result) {
    var parsedData = angular.fromJson(result.data);
});

或者,对于好的衡量标准,在香草JS中:

var parsedData = JSON.parse(result.data);