Return 来自控制器的动态数组 Asp.Net MVC

Return Dynamic Array From Controller Asp.Net MVC

我可以使用下面的代码生成饼图就像图片一样

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

现在我要做的是从 Controller 动态生成 var data = []。这该怎么做?数据也来自数据库。

您可以在控制器发生就绪事件时调用,并且在获取数据(从控制器返回 Json 后)可以进一步处理。你可以像下面这样尝试

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

很简单,只需 return Json 来自您的控制器:

首先为属性创建一个模型class

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

MVC 动作方法:-

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

Ajax 调用:-

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

通过合并 Pranav Patel and Ghanshyam Singh 个答案 我能够达到所需的输出

型号

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

控制器

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

业务层

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

查看

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