Reputation: 302
Using C# and the ASP.Net architecture, I'm trying to display a morris.js chart. Nevertheless, I don't completely understand how to adapt my c# List<List<int>>
to the required format. Any ideas ?
Here is my code :
1) How I build my list in C#
public List<List<int>> DataModel { get; private set; }
public void GenerateDataModel()
{
List<List<int>> tempo = new List<List<int>>();
Random rnd = new Random();
for (int i = 0; i < 100; i++)
{
List<int> un = new List<int>() { i, rnd.Next(10) };
tempo.Add(un);
}
DataModel = tempo;
for (int i = 0; i < 100; i++)
{
System.Diagnostics.Debug.WriteLine(DataModel[i][0]);
System.Diagnostics.Debug.WriteLine(DataModel[i][1]);
}
}
2) How I implement the morris script : (inspired of this question)
<script>
var datas = @Model.DataModel;
var myArray = [];
var z = 0;
for (var tot = @Model.DataModel.Count(); z < tot; z++) {
myArray.push({ 'year': datas[z][0], 'value': datas[z][1]});
}
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'myfirstchart',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: myArray,
// The name of the data record attribute that contains x-values.
xkey: 'year',
// A list of names of data record attributes that contain y-values.
ykeys: ['value'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Value']
});
</script>
What I finally get (should be something in the "sales" box):
Upvotes: 0
Views: 509
Reputation: 1480
The content of your <script>
tag is processed both by the server and by the browser. The server processes parts starting with @
then it sends the result to the browser which runs the JavaScript code.
When you specify just an expression after @
the server replaces that with the value of the expression. If the value is an object, you'll get a result of .ToString()
called on that object. For your List<List<int>>
it won't be too pretty or useful:
var datas = System.Collections.Generic.List`1[System.Collections.Generic.List`1[System.Int32]];
You can check that by using F12 tools in your browser.
There are multiple way to adjust your code to achieve the result you want.
First, you can just use Newtonsoft.Json library which is already included in every ASP.NET project anyway. Add @using Newtonsoft.Json.Linq;
at the top of your view in 2), then replace your assignment to datas
with the following:
var datas = @JArray.FromObject(Model.DataModel).ToString(Newtonsoft.Json.Formatting.None);
Second, you can generate your myArray
structure on the server by pulling the for
loop from JavaScript into C#:
var myArray = [
@for (var i = 0; i<Model.DataModel.Count; i++)
{
@:{ 'year': @Model.DataModel[i][0], 'value': @Model.DataModel[i][1] },
}
];
Upvotes: 1