将json数据从控制器传递到视图

时间:2015-03-18 05:22:56

标签: jquery json asp.net-mvc controller c3

部分视图:

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

控制器Json代码

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

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

请帮忙。

1 个答案:

答案 0 :(得分:3)

您不是从方法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.');                    
         }
       });
相关问题