Robert Ross Robert Ross - 4 years ago 103
C# Question

How to properly pass json to a view

I have a view with some javascript code for a pie chart in it. This view has an action method, where I am running some queries an converting the results to json in order to fill the pie chart with something.

The problem is that I don't know (and couldn't understand from another questions here) how to properly return a json from action to view and actually work with the data in some way in the view.

Currently, what I have give me a json string in my browser instead of a view.

I do not have a model in my project for the data that's in in the json.

Here's all the code from my view :

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




google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Language', 'Speakers (in millions)'],
['German', 5.85],
['French', 1.66],
['Italian', 0.316],
['Romansh', 0.0791]
]);

var options = {
legend: 'none',
pieSliceText: 'label',
title: 'Accumulated experience',
pieStartAngle: 100,
};

var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>



<div id="piechart" style="width: 1000px; height: 600px;"></div>


And here is my controller :

public ActionResult experiencePieChart()
{
//some queries
var json = JsonConvert.SerializeObject(perclist);
return Json(json, JsonRequestBehavior.AllowGet);
}

Answer Source

your controller method should return JsonResult, just change it's signature in following way:

public JsonResult experiencePieChart()
{
    var perclist = ...
    //some queries
    return Json(perclist, JsonRequestBehavior.AllowGet);
}

then in your js code you could call it

$(document).ready(function()
{
    $.get("/YourController/experiencePieChart",ShowPieChart,"json").fail(ShowPieChartFail);
});

of course then you need define ShowPieChart function which will render that graph

function ShowPieChart(chartData){
    // this code will be executed after result is returned asynchronously
    // chartData contains JSON representation of perclist variable
}

In case you'd like to do that data-transfer just on each refresh of page, you could store data required for chart. In your .cshtml you'd just add

<script type="text/javascript">
    var ChartData = @Html.Raw(Json.Encode(@Model.MyData))
</script>

then during execution of js on client side you'd have ChartData variable initialized. Anyway this way have multiple downside and is not scalable at all. Going with ajax call seems much better to me.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download