How to pass json data from controller to view

Total Post:52

Points:366
C#  JSON  Mvc 
C#
 1038  View(s)
Ratings:
Rate this:

 Partial 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 code 

public string GetData()
{
return "{ 'indicator': 'A', 'total': 10 },{ 'indicator': 'B', 'total': 20 },{ 'indicator': 'C', 'total': 30 }";

can any one solve my problem ...my problem is When i use the above code it doesn't work but if I pass json data as specified in this JS Fiddle link, it works. Am I passing the JSON data incorrectly from controller.?

Please help.

Thanks in Advance

  1. Post:45

    Points:323
    Re: How to pass json data from controller to view

    You are not returning JSON from method GetData. Do this way to return 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 calling like this

    $.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.');
              }
          });

     Hope this helps you..

      Modified On Apr-11-2018 10:57:37 PM

Answer