Thursday, 15 August 2013

asp.net mvc - How to attach sql database to a javascript graph -



asp.net mvc - How to attach sql database to a javascript graph -

i'm creating website using asp mvc5 , need show info on view using graph. have implemented graph using javascript.

<head> <script src="../../js/jquery-1.11.1.min.js"></script> <script src="../../js/chart.script.js"></script> @*<link rel="stylesheet" href="../../css/finalstylesheet.css">*@ </head> <body> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading">daily booking</div> @*<div class="panel-body">*@ @*<div class="col-lg-2"></div> <div class="col-lg-8" style="background-color:#4876ff;">show</div> <div class="col-lg-2"></div>*@ <br><br> <div class='wrapper'> <canvas height='150' id='canvas' width='170'></canvas> </div> @*</div>*@ </div> </div> <script> var mydata = { labels: ["9:00", "12:00", "15:00", "18:00"], datasets: [ { fillcolor: "rgba(072,118,225,.5)", strokecolor: "rgba(001,001,190,1)", pointcolor: "rgba(001,001,190,1)", pointstrokecolor: "#fff", data: [40, 25, 90, 40] } ] } new chart(document.getelementbyid("canvas").getcontext("2d")).line(mydata) </script> </body>

i have database.

<add name="defaultconnection" connectionstring="data source=acer-pc\cad;initial catalog=it;integrated security=true;" providername="system.data.sqlclient" />

i want values customer_age table , show in graph. how supposed that?

without knowing construction of customer_age table, should help along way:

use ajax phone call fetch info mvc controller action (or, more efficiently, web api method). then, when info returns, build chart. looks chart needs 2 info arrays: 1 labels , other values. instead of providing 2 separate ajax endpoints homecoming 2 series we'll homecoming array of objects, each of has 2 properties: label , corresponding value.

e.g.:

$.ajax ({ url: 'url.action("youraction","yourcontroller")', //data: {} //include if need pass parameters query type: 'get', success: function(result) { if (!result.success) alert(result.message); else { var mydata = { labels: result.data.map(function(i){return i.label;}), datasets: [ { fillcolor: "rgba(072,118,225,.5)", strokecolor: "rgba(001,001,190,1)", pointcolor: "rgba(001,001,190,1)", pointstrokecolor: "#fff", data: result.data.map(function(i){return i.value;}) } ] } new chart(document.getelementbyid("canvas").getcontext("2d")).line(mydata) } } });

the controller action this:

[httpget] public actionresult getchartdata() { seek { //get info repository var info = customerrepository.getchartdata(); //convert format expected javascript - should done in repository method homecoming json(new { success=true, info = (from d in info select new {label = d.label, value=d.value}).toarray() }, jsonrequestbehavior.allowget); } grab (exception e) { homecoming json(new {success=false, message=e.message}, jsonrequestbehavior.allowget); } }

javascript asp.net-mvc database-connection

No comments:

Post a Comment