Solved

Use Javascript Object from c# Webmethod as datasource for morris.js graph

Posted on 2015-01-09
1
874 Views
Last Modified: 2015-01-12
Hi from my webmethod datatable how would I use my js dataobject to as the datasource for a morris graph?

   
     [WebMethod]
        public static string buildagraph()
        {
            DataTable dt = new DataTable();
            using(SqlConnection connGraph = new SqlConnection())
            {
                using (SqlCommand cmdGraph = new SqlCommand("select PeriodValue, sum(CallsAnswered) as 'CA' from table where PeriodType = 'Month' group by PeriodValue", connGraph))
                {
                    connGraph.Open();
                    SqlDataAdapter daGraph = new SqlDataAdapter(cmdGraph);
                    DataSet dsGraph = new DataSet();
                    daGraph.Fill(dsGraph);
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                    Dictionary<string, object> row;
                    foreach (DataRow dr in dt.Rows)
                    {
                        row = new Dictionary<string, object>();
                        foreach (DataColumn col in dt.Columns)
                        {
                            row.Add(col.ColumnName, dr[col]);
                        }
                        rows.Add(row);
                    }
                    return serializer.Serialize(rows);
                }
            }
        }

Open in new window


$(document).ready(function () { 
            $.ajax({
                type: "POST",
                data: "{}",
                url: 'josn.aspx/buildagraph',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    //alert('success')
                    alert(data.d);
                    var pardata = JSON.parse(data.d);       
                },                
                error: function () {
                    alert('failure');
                }
            });
        });

Open in new window


<body>
    <form id="form1" runat="server">
    <div>
        <div id="myfirstchart" style="height: 550px;"></div>    
    </div>
    </form>
    <script>
    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: [
    { year: '2008', value: 20 },
    { year: '2009', value: 10 },
    { year: '2010', value: 5 },
    { year: '2011', value: 5 },
    { year: '2012', value: 20 }
  ],
   //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>
</body>

Open in new window

0
Comment
Question by:Scarlett72
1 Comment
 
LVL 42

Accepted Solution

by:
Rob Jurd, EE MVE earned 500 total points
ID: 40541439
http://jsbin.com/daxiso/4/edit?js,output shows how you can load data from an external source via ajax and when it returns, creates the chart

html:
<div id="myfirstchart" style="height: 250px;"></div>

Open in new window


function createChart(chart_data) {
  var mychart = 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: chart_data,
    // 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']
  });
}

$(function() {
  $.ajax({
    method: 'get',
    dataType: 'text',
    url: 'http://jsbin.com/qafed.json', 
    success: function(a,b,c) {
      var data = JSON.parse(a);
      createChart(data);
    },
    error: function(e) {
      console.log('error');
    }
  });
});

Open in new window


external data (http://jsbin.com/qafed/2/edit?js):
**NOTE that JSON requires double quotes.  Do NOT use single quotes.
[
  { "year": "2008", "value": 20 },
  { "year": "2009", "value": 10 },
  { "year": "2010", "value": 5 },
  { "year": "2011", "value": 5 },
  { "year": "2012", "value": 20 }
]

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Sums of coloumns in html/java 15 66
Polygon I google maps 1 14
How can I echo a PHP variable in AJAX function? 7 32
Detect change of Select using JavaScript Only 12 46
These instructions are based on installing Owncloud on your new raspberry pi connected with a usb HDD. What do you need Part A? A Raspberry Pi, model B. A boot SD card for the Raspberry Pi. A usb HDD An Ethernet cable to connect to the lo…
Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now