如何在javascript中注册一个数组,而不是在ASP.NET中加载页面?
我在aspx.cs文件中使用以下代码:如何在javascript中注册一个数组,而不是在ASP.NET中加载页面?,javascript,c#,asp.net,Javascript,C#,Asp.net,我在aspx.cs文件中使用以下代码: String arrName = "MyArray"; String arrValue = "\"1\", \"2\", \"text\""; // Define the hidden field name and initial value. String hiddenName = "MyHiddenField"; String hiddenValue = "3"; // Get a ClientSc
String arrName = "MyArray";
String arrValue = "\"1\", \"2\", \"text\"";
// Define the hidden field name and initial value.
String hiddenName = "MyHiddenField";
String hiddenValue = "3";
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Register the array with the Page class.
cs.RegisterArrayDeclaration(arrName, arrValue);
// Register the hidden field with the Page class.
cs.RegisterHiddenField(hiddenName, hiddenValue);
这是来自客户端的代码
function onClick(rowIndex, cellIndex)
{
alert(MyArray[0]);
}
如果我尝试在javascript上检索MyArray的任何值,如果该代码进入代码的Page_Load部分,我可以毫无问题地进行检索,但是如果我尝试从代码的其他位置调用它,从我必须调用的位置调用它,虽然代码执行了,但似乎忽略了数组的注册,因为在javascript中尝试从MyArray获取任何结果时出现了错误
我觉得这个错误很奇怪,但事实就是这样。。。您能试着找出可能发生的情况吗?好吧,我一直在成功运行您的代码,尽管您的问题我并不完全清楚:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="Test.WebForm3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>ClientScriptManager Example</title>
</head>
<body>
<form id="Form1" runat="server">
<input type="text" id="Message" />
<input type="button" onclick="onClick()" value="Run Script" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
<script>
function onClick(rowIndex, cellIndex) {
alert(MyArray[0]);
}
</script>
</body>
</html>
必须通过单击按钮来运行代码,然后它才能工作您还没有告诉我们错误是什么。如果你想让我们解释为什么会发生这样的事情,这似乎是一个非常重要的细节。您还没有显示任何客户端脚本来解释错误发生的位置。错误是没有定义MyArray,代码只是我现在输入的小代码。如果从OnLoad调用,则显示1,但是,如果从其他区域调用,则会出现错误。您从何处调用RegisterArrayDeclaration?我必须从我自己开发的函数调用它,如果从Page_Load调用,则它会工作。@MyKet因此,您开发的函数可能在首次请求页面时根本不会被调用,因此您的数组没有注册。可能您的问题是您试图使用尚未运行的代码?没有,我进入了调试模式并检查了它是否已运行。谢谢你的提示。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Test
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String arrName = "MyArray";
String arrValue = "\"1\", \"2\", \"text\"";
// Define the hidden field name and initial value.
String hiddenName = "MyHiddenField";
String hiddenValue = "3";
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Register the array with the Page class.
cs.RegisterArrayDeclaration(arrName, arrValue);
// Register the hidden field with the Page class.
cs.RegisterHiddenField(hiddenName, hiddenValue);
}
}
}