Solved

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

Posted on 2015-01-09
1
843 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
Comment Utility
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
New Relic recently released its Synthetics product that allows for the creation of performance monitors that periodically test a site's performance. If you wish to test an interactive workflow New Relic employs Selenium WebDriverJS to run those test…
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)

772 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

11 Experts available now in Live!

Get 1:1 Help Now