页面加载时未插入脚本
Script not inserted on page load
我正在研究一个模拟类,我需要从数据库中获取数据并将其发送到json array
到javascript。然而,我不能让它工作,我已经遵循了几个教程和例子,它看起来像我错过了一些东西。
CodeBehind
文件中的代码:
public class Segment : System.Web.UI.Page
{
public int[,] GetAllSegments()
{
int[,] segments = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
return segments;
}
public void Page_Load(object sender, EventArgs e)
{
int[,] allSegments = GetAllSegments();
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(allSegments);
string script = String.Format("<script type='"text/javascript'">var allSegments={0}</script>", json);
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "clientScript", script, true);
}
}
脚本从未出现,我也尝试过RegisterStartupScript
,但这也不起作用…
在我的HTML页面中,我在顶部包含了以下内容:<%@ Page Language="C#" CodeBehind="Dashboard.aspx.cs" %>
有人能发现问题吗?任何帮助都非常感激!
关键是,RegisterClientScriptBlock
方法中的最后一个参数被命名为addScriptTags
,因为您已经将其设置为true
,您应该删除脚本标签并让c#为您添加这些标签:
int[,] allSegments = GetAllSegments();
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(allSegments);
string script = String.Format("var allSegments={0};", json);
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "clientScript", script, true);
或者将addScriptTags
设置为false
:
int[,] allSegments = GetAllSegments();
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(allSegments);
string script = String.Format("<script type='"text/javascript'">var allSegments={0};</script>", json);
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "clientScript", script, false);
我所做的另一个小改变是在js代码的末尾添加分号。
相关文章:
- 为什么使用Bookshelf.js插入脚本会挂起
- 如何动态插入脚本标签
- 插入脚本以使用 django 在提供模板页面时运行
- 在标头标记中插入脚本和链接标记
- 反应.js从远程 CDN 插入脚本标记
- innerHTML在正文中插入脚本(用于ZeroClipboard)不起作用
- 哪些jQuery命令用于在html中插入脚本标签(包含计数器定时器)
- 使用react插入脚本标签,脚本不包含javascript代码
- 如何在React中插入脚本标签
- 为什么用jQuery在头部插入脚本如此奇怪?
- 在Durandal中插入脚本标签
- 如何插入<脚本>标签在Django管理页面上
- 使用Jquery插入脚本标签
- 在另一个脚本之前动态插入脚本会使函数返回未定义
- Angular2动态插入脚本标签
- Azure移动服务-在插入脚本上更改用户模型
- 在DOM中动态插入脚本
- 使用jQuery在文本区插入脚本标签
- 在IE中插入脚本和iframe标签
- 动态插入脚本在谷歌应用程序脚本web应用程序