简体   繁体   中英

How to pass values from Controller to Javascript in MVC4?

I am new to MVC4 with Entity Framework. Now I am getting the count and key values of column, and storing them into a varible. I want to pass that variable to JavaScript, to get those values and to assign them into chart. How can I get dynamic chart based on the number of programs?

Now I am using ViewBag temporarily.

This is my controller code:

var qry = db.Tbl_Mst_Programs.Where(r => r.Program != null)
                                           .GroupBy(r => r.Program)
                                           .Select(gr => new { key = gr.Key, Count = gr.Count() }).ToList(); 

 var internship = qry[0];
            var ltv = qry[1];
            var mtv = qry[2];
            var workCampus = qry[3];

            ViewBag.internship = internship;
            ViewBag.ltv = ltv;
            ViewBag.mtv = mtv;
            ViewBag.workCampus = workCampus;
            return View();

This is my view code for chart:

<script type="text/javascript">
        var internship = @ViewBag.internship;
        var ltv=@ViewBag.ltv;
        var mtv=@ViewBag.mtv;
        var worcmps=@ViewBag.workCampus;

     var testdata = [
    {
        key: "Internship",
        y: internship
    },
    {
        key: "LTV",
        y: ltv
    },
    {
        key: "MTV",
        y: mtv
    },
    {
        key: "Work Campus",
        y: worcmps
    }
  ];

    function thirtySeries() {
            var data = [];
            for (var i = 0; i < 30; i++) {
                data.push({
                    key: "Series-" + i,
                    y: Math.floor(Math.random() * 100)
                });
            }
            return data;
        }

        function defaultChart(containerId, data, labelType) {
            nv.addGraph(function () {
                var width = 300,
          height = 300;

                var chart = nv.models.pieChart()
          .x(function (d) { return d.key })
          .y(function (d) { return d.y })
          .color(d3.scale.category10().range())
          .width(width)
          .height(height)
          .labelType(labelType)
          ;

                d3.select("#" + containerId + " svg")
            .datum(data)
          .transition().duration(1200)
            .attr('width', width)
            .attr('height', height)
            .call(chart);

                nv.utils.windowResize(chart.update);
                return chart;
            });
        }

如果您在视图对象中拥有数据,则只需按以下方式对其进行访问即可:

var ltv =  '@Model.ltv';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM