Tron Bekker
Tron Bekker

Reputation: 83

Call google chart from partial view in mvc

I'm trying to call google chart from a partial view to a view but the chart is not loading. It was working fine in the view, but when converted to partial view it is not rendering. Anyone please check and help me if anything wrong.

My View

@model HeathAppDesign.Model.ChartModel
@{
    ViewBag.Title = "Index";
}
<h2>
    Index</h2>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


<script type="text/javascript">
    $(document).ready(function () {
        $('#ChartTypes').change(function () {


            var selectedID = $(this).val();
            $.ajax({
                url: '/charts/GetChart/4',
                type: 'GET',
                success: function (result) {
                    debugger;
                    var res = JSON.stringify(result);
                    $('#div-Graph').append(res);
                    alert($('#div-Graph').html());
                }
            });

        });
    });
</script>
<div>


    <select id="ChartTypes">
        <option id="Chart1" value="0">Projected Annual Cost per Member</option>
        <option id="Chart2" value="1">Projected Annual Cost to Employer by Plan</option>
        <option id="Chart3" value="2">Total Projected Cost</option>
        <option id="Chart4" value="3">Renewal Year PMPM Cost</option>
        <option id="Chart5" value="4">Paid Or Allowed Ratio by Plan</option>
        <option id="Chart6" value="5">Impact of Plan Design Changes on 2017 Costs</option>
        <option id="Chart7" value="6">5 Year Projected Plan Change Impact</option>
        <option id="Chart8" value="7">Impact of Trend Over Time</option>
    </select>
    <div id="div-Graph">

    </div>
</div>

My PartialView

@model IEnumerable<HeathAppDesign.Model.ChartModel>


<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] }); 


</script>
<script type="text/javascript">
    $(function () {

        chartsdata = '@Model'
        alert(chartsdata);
        google.charts.load('current', { 'packages': ['bar'] });
        google.charts.setOnLoadCallback(drawStuff);

        function drawStuff() {
            var data = new google.visualization.DataTable();

            data.addColumn('string', '');
            data.addColumn('number', '');

            for (var i = 0; i < chartsdata.length; i++) {
                data.addRow([chartsdata[i].XCoordinates, chartsdata[i].YCoordinates]);
            }

            var options = {
                title: 'Paid/Allowed Ratio by Plan',
                width: 500,
                legend: { position: 'none' },
                trendlines: { 0: {} },
                bars: 'vertical', // Required for Material Bar Charts
                vAxis: { viewWindow: { min: 90, max: 100 }, gridlines: { count: 11} },

                bar: { groupWidth: "20%" }
            };

            var chart = new google.charts.Bar(document.getElementById('chartdiv'));
            chart.draw(data, options);
        };


    });

</script>
<h2>
    Chart5</h2>
<div id="chartdiv" style="width: 600px; height: 350px; margin: 0 auto;">
</div>

My ActionMethod

 [HttpGet]
        public ActionResult GetChart(int id)
        {
            return PartialView("_PaidOrAllowedRatio",
                      objChartService.GetChartCoordinates(ChartTypes.PaidOrAllowedRatioByPlan));
        }

My result is like this

"\r\n\r\n \r\n Chart5

\r\n \r\n \r\n" Design table Area

I have multiple charts in the same view and that is why using partial view.

Anyone please help?

Upvotes: 0

Views: 1151

Answers (2)

Tron Bekker
Tron Bekker

Reputation: 83

Finally I found an answer, really taken lots of time to fix this. I moved all script references to my view file from my partial view and then called the google.load in view

ie,

google.load("visualization", "1", { packages: ["corechart"] }); 

So my view became like below

@model HeathAppDesign.Model.ChartModel
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>


<script type="text/javascript">
    **google.load("visualization", "1", { packages: ["corechart"] });** 

    $(document).ready(function () {
        $('#ChartTypes').change(function () {
            var selectedID = $(this).val();
            $.ajax({
                url: '/charts/GetChart/',
                data: {id:4},
                type: 'GET',
                success: function (result) {

                    $('#div-Graph').append(result);

                }
            });

        });
    });
</script>
<div>


    <select id="ChartTypes">
        <option id="Chart1" value="0">Projected Annual Cost per Member</option>
        <option id="Chart2" value="1">Projected Annual Cost to Employer by Plan</option>
        <option id="Chart3" value="2">Total Projected Cost</option>
        <option id="Chart4" value="3">Renewal Year PMPM Cost</option>
        <option id="Chart5" value="4">Paid Or Allowed Ratio by Plan</option>
        <option id="Chart6" value="5">Impact of Plan Design Changes on 2017 Costs</option>
        <option id="Chart7" value="6">5 Year Projected Plan Change Impact</option>
        <option id="Chart8" value="7">Impact of Trend Over Time</option>
    </select>
    <div id="div-Graph">

    </div>
</div>
<div>
    Design table Area
</div>

Thanks everyone for your time!

Upvotes: 0

Shyju
Shyju

Reputation: 218732

I see few problems with your code

Issue 1

In your partial view, this line

var chartsdata = '@Model';

When razor executes this code, It generates code like below (you can see this if you check view source of the generated page.(check response tab of your ajax call))

var chartsdata = 'System.Collections.Generic.List`1[YourNamespace.ChartModel]';

This is a string. So basically in your for loop below you are looping until the length of this string , which is obviously wrong! Your Model is a collection of ChartModel. So you should set the same collection/array as it is to this chartsdata variable which you can loop through later and use it for adding the data for the graph.

You can use JsonConvert.SerializeObject with Html.Raw to convert your model object to a javascript array.

var chartsdata = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));

This will store an array (of ChartModel objects(js version)) to the chartsdata variable.

Now your looping code is good

for (var i = 0; i < chartsdata.length; i++) {
   data.addRow([chartsdata[i].XCoordinates, chartsdata[i].YCoordinates]);
}

Issue 2

Next problem is, you are using a wrong variable to update the DOM when you get the ajax call response.

success: function (result) {                  
                $('#div-Graph').append(res);   // WHAT IS "res" ?????                  
            }

The fix is simple

success: function (result) {                  
                $('#div-Graph').append(result);                   
            }

Once you fix these issues, the charts will appear on the SELECT element change event ,assuming you do not have any other js errors in the page.

Upvotes: 1

Related Questions