Reputation: 73
I have an MVC application with CHart.js. Iam able to load the CHart.js on the View load event.
I want the Chart.js to be loaded on a html button click event. On button click the controller is invoked and based on the search condition data is filtered. I want this filtered content to be displayed on the chart.js.
How do i invoke the javascript function to load the chart on button click after the controller process is done on button click.
Flow should be 1. Enter the filter conditions 2. click button 3. controller fetches the data from the database based on filters 4. then the javascript function in the view is invoked to load the chart.js
Let me know how it has to be done.
Upvotes: 0
Views: 2940
Reputation: 413
For displaying data returned from your Controller in JavaScript you have two options:
The First:
using the razor syntax inside your View to refer to the model returned by the controller. This means that your JavaScript would also be written inside your View.
@model 'yourViewModel'
<div>
//your view html code
</div>
<script>
document.getElementById("button").click(function() {
var chartData= @Html.Raw(Json.Serialize(Model.'nameOfYourModel'));
var ctx = document.getElementById("myChart").getContext('2d');
var myLineChart = new Chart(ctx, {
type: 'line',
data: chartData,
options: options
});
</script>
The Second:
Retrieve the data from your controller trough AJAX, for this I would recommend using the jQuery library. As it makes the syntax easier to write and understand.
var chartData;
$('.button').click(function() { //your button
$.ajax({ // Invoke controller action to retrieve data
url: "path to your controller and its action",
type: 'GET',
success: function(data){
chartData = data;
}
});
var ctx = $("myChart").getContext('2d');
var myLineChart = new Chart(ctx, {
type: 'line',
data: chartData,
options: options
});
}
With this approach you call the controller action that returns your chart data in JSON format.
Upvotes: 2