4

I can generate a Pie Chart Just like the picture by using the code below

enter image description here

<script>
         var pieChartData = [
        { label: "Data 1", data: 16, color: "#62cb31", },
        { label: "Data 2", data: 6,  color: "#A4E585", },
        { label: "Data 3", data: 22, color: "#368410", },
        { label: "Data 4", data: 32, color: "#8DE563", }
    ];

    var pieChartOptions = {
        series: {
            pie: {
                show: true
            }
        },
        grid: {
            hoverable: true
        },
        tooltip: true,
        tooltipOpts: {
            content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
            shifts: {
                x: 20,
                y: 0
            },
            defaultTheme: false
        }
    };

    $.plot($("#_ByRegion"), pieChartData, pieChartOptions);
</script>

Now what I want to do is to generate the var data = [] dynamically from Controller. How to do this? Also the data is from the Database.

2
  • Use ajax call and return 2d array from controller Commented Feb 24, 2017 at 6:31
  • @SorangwalaAbbasali any example on how to do that? :) Commented Feb 24, 2017 at 6:35

3 Answers 3

3

By Combining Pranav Patel and Ghanshyam Singh answers I was able able to reach the desired output

Model

public class GenderPieChart_Model
{
    public string GenderDesc { get; set; }
    public int GenderID { get; set; }
}

Controller

public JsonResult Gender()
{
     Dashboard_Layer data = new Dashboard_Layer();
     var lst = data.Gender();
     return Json(lst, JsonRequestBehavior.AllowGet);
}

Business Layer

public IEnumerable<GenderPieChart_Model> Gender()
    {
        List<GenderPieChart_Model> data = new List<GenderPieChart_Model>();
        using (SqlConnection con = new SqlConnection(Connection.MyConn()))
        {
            SqlCommand com = new SqlCommand("dbo.sp_Project_DashBoard 4", con);
            con.Open();
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                GenderPieChart_Model value = new GenderPieChart_Model();
                value.GenderDesc = Convert.ToString(reader.GetValue(0));
                value.GenderID = Convert.ToInt32(reader.GetValue(1));
                data.Add(value);
            }
        }
        return data;
    }

View

<div class="flot-chart-content" id="_ByGender" style="height: 150px"></div>
<script>
$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: "@Url.Action("Gender", "Dashboard")",
        content: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var myData = data;
            var pieChartData = [];
            $.each(data, function (i,v) {
                pieChartData.push({ label: v.GenderDesc, data: v.GenderID, color: "#62cb31", });
            })
            var pieChartOptions = {
                series: {
                    pie: {
                        show: true
                    }
                },
                grid: {
                    hoverable: true
                },
                tooltip: true,
                tooltipOpts: {
                    content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
                    shifts: {
                        x: 20,
                        y: 0
                    },
                    defaultTheme: false
                }
            };
            $.plot($("#_ByGender"), pieChartData, pieChartOptions);
        }
    })

});
</script>
Sign up to request clarification or add additional context in comments.

Comments

2

you can call when your controller on ready event and after getting data (returned Json from your controller) can process further. You can try like below

<script>
$(document).ready(function(){
    $.ajax({
        type: "POST", //GET or POST
        url: "<YOUR URL>",
        data: "<YOUR PARAMETER IF NEEDED>",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){ //data is your json returned from controller
        var myData = JSON.parse(data);

        //create your 'pieChartData' from object 'myData'
        //pieChartData = 

        var pieChartOptions = {
            series: {
                pie: {
                    show: true
                }
            },
            grid: {
                hoverable: true
            },
            tooltip: true,
            tooltipOpts: {
                content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
                shifts: {
                    x: 20,
                    y: 0
                },
                defaultTheme: false
            }
        };

        $.plot($("#_ByRegion"), pieChartData, pieChartOptions);
        }
    });
});
</script>

1 Comment

It would say Unexpected token o in JSON at position
2

Its simple just return Json from your controller:

first create a model class for the properties

public class Chart
{
    public string label{get;set;}
    public string data{get;set;}
    public string color{get;set;}
}

MVC action method:-

public JsonResult Chart()
{
   List<Chart> chartList=new List();
   // Code to fetch Data in List chartList
   return Json(chartList,JsonRequestBehaviour.AllowGet);
}

Ajax Call:-

<script>
$(document).ready(function(){
    $.ajax({
        type: "POST", //GET or POST
        url: "/Controller/Chart",
        data: "<YOUR PARAMETER IF NEEDED>",
        dataType: "json",
        success: function(data){ 
          $.each(data,function(i,index){
          // Code to plot Chart here

          });
         }

    });
});
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.