简体   繁体   中英

Changing JS Code from Code behind

I'm trying to draw a chart on my website. Here is the js code for the chart with sample inputs

 <script type="text/javascript"> $(function () { var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]];//these are sample $.plot("#placeholder", [d2]); }); </script> 

Here is what i wanna do. I want to take some information from the database and put it to the chart. I wrote down the code for taking information. But i couldn't manage how to insert them to the js code for the chart.

using (var db = new Entities())
{ var q = from u in db.Sites
          where u.SiteURL == result.SiteURL
          select u;
if (q.Any()) {
        List<webpagespeedtest_flat.DataModel.Sites> l = new List<webpagespeedtest_flat.DataModel.Sites>();
        l = q.OrderByDescending(s => s.CheckDate).Take(10).ToList();
        webpagespeedtest_flat.DataModel.Sites[] z = l.ToArray();
int x = z.Count();
for( int i=0; i < z.Count(); i++){
 z[i].Score; // --> this will be the first attribute(x)
 z[i].CheckDate;// -->this will be the second attribute(y)
}

Assuming you're using MVC, there are two ways you could do this. One is to use razor to emit the correct javascript that you need when the page is rendered. The other (neater) way is to make a call that returns JSON which is then used to populate the chart.

You can use from c# like this.

System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append(@"<script type='text/javascript'>");
    sb.Append(@"$(function () {");
    sb.Append(@"var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]];");
    sb.Append(@"$.plot(\""#placeholder\"", [d2]);");
    sb.Append(@"});");
    sb.Append(@"</script>");
    ScriptManager.RegisterStartupScript(this, this.GetType(), "ChangeChart", sb.ToString(), false);

Sorry if i can not help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM