简体   繁体   English

从后面的代码更改JS代码

[英]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 这是带有示例输入的图表的js代码

 <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. 但是我无法管理如何将它们插入图表的js代码中。

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. 假设您使用的是MVC,则有两种方法可以执行此操作。 One is to use razor to emit the correct javascript that you need when the page is rendered. 一种是使用剃刀发出呈现页面时所需的正确javascript。 The other (neater) way is to make a call that returns JSON which is then used to populate the chart. 另一种(更简洁的)方法是进行一个返回JSON的调用,然后将其用于填充图表。

You can use from c# like this. 您可以像这样在c#中使用。

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. 对不起,如果我不能帮你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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