Solved

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

Posted on 2015-01-09
1
1,014 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 43

Accepted Solution

by:
Rob 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

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article discusses how to implement server side field validation and display customized error messages to the client.
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)

719 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