从页面访问变量值(循环.aspx.cs 到 Java 脚本

access a variable value(which is in loop) from .aspx.cs page to java script

本文关键字:cs aspx Java 脚本 循环 访问 变量值      更新时间:2023-09-26

我的.aspx.cs文件中有循环。

foreach (DataRow DRow in DT_Test_Question.Rows)
{
    Question_ID = DRow[1].ToString();
}

我想在没有回发的情况下访问 java 脚本中的Question_ID,但Question_ID给了我最后一个值。如何获取Question_ID的所有值?

aspx.cs 文件使用以下代码

public string Question_ID = "";
protected void Page_Load(object sender, EventArgs e)
{
   foreach (DataRow DRow in DT_Test_Question.Rows) 
   {
        Question_ID += DRow[1].ToString() + ",";
   }
}

对 ASPX 使用以下代码

<script type="text/javascript">
  var Question_ID = '<%=Question_ID.Trim(',')%>'.split(',');
  .
  .
  // you can use Question_ID is array of string
</script>

注意:Question_ID 在 javascript 中使用它之前,必须具有值,因此赋值将在 page_load/init 方法上完成。另请注意Question_ID必须是公共变量才能在 javascript 中访问它。

有一个隐藏字段来保存所有Question_ID,如下所示...

StringBuilder question_IDs = new StringBuilder();
foreach (DataRow DRow in DT_Test_Question.Rows)
{
    if (DRow[1] != null)
    {
        Question_ID = DRow[1].ToString();
        if (question_IDs.length == 0)
            question_IDs.Append(Question_ID);
        else
            question_IDs.Append("," + Question_ID);
    }
}
hdnField.Value = question_IDs.ToString();