jquery - 将 json 数据从 Controller 传递到 View

标签 jquery json asp.net-mvc controller c3

部分 View :

var dataa;
    $.ajax({
        url: ServerUrl + '/Dashboard/GetData',
        type: 'POST',
        cache: false,
        dataType: 'text',
        async: true,
        error: function (xhr) {
            //alert('Error: ' + xhr.statusText);
        },
        success: function (result) {
            debugger;
            dataa = result;
            var chart = c3.generate({
                data: {
                    type: 'bar',
                    json: [
                        dataa
                    ],
                    keys: {
                        x: 'indicator',
                        value: ['total']
                    }
                },
                axis: {
                    x: {
                        type: 'category'
                    }
                },
                bar: {
                    width: {
                        ratio: 0.5
                    }
                }
            });
        }
    });

Controller Json代码

public string GetData()
{
return "{ 'indicator': 'X', 'total': 100 },{ 'indicator': 'Y', 'total': 200 },{ 'indicator': 'Z', 'total': 300 }";
}

当我使用上面的代码时,它不起作用,但是如果我传递 this JS Fiddle 中指定的 json 数据链接,它有效。我是否从 Controller 错误地传递了 JSON 数据?

请帮忙。

最佳答案

您不会从 GetData 方法返回 JSON。 这样做返回JSON

public JsonResult GetData()
   { 
       var data = new[] {
          new { indicator= "X", total = 100 },
          new { indicator= "Y", total = 200 },
          new { indicator= "Z", total = 300 }
       };

           return  Json(data,JsonRequestBehavior.AllowGet);
   }

并进行 ajax 调用,如下所示:

 $.ajax({
         cache: false,
         type: "GET",
         url:URL,
         dataType: 'json',
         success: function (result)
         {
           console.log(result);
         },
         error: function (xhr, ajaxOptions, thrownError)
         {
          alert('Failed to retrieve data.');                    
         }
       });

关于jquery - 将 json 数据从 Controller 传递到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29114665/

相关文章:

python - Django 模型的初始数据

json - Postgres 中 JSON 和 JSONB 的区别

asp.net-mvc - 使用 MVC Futures 的异步 Controller 在 .NET 3.5 SP1 中的 ASP.NET MVC 1 中长轮询的服务器和连接限制

asp.net-mvc - 为什么我的 HtmlHelper 扩展不起作用?

javascript - 使用 jQuery 翻转图像

PHP 处理 JSON 发送的数据

javascript - Bootstrap 轮播分页/幻灯片编号问题

javascript - 使用具有用户定义字段的新请求者创建新的 Zendesk 票证

javascript - AJAX 刷新期间丢失 "click"事件

c# - 如何从基于 Azure 的 MVC 应用程序启用提醒?