传递List<int>作为Javascript函数的参数

Pass List<int> as argument of Javascript function

本文关键字:函数 Javascript 参数 作为 int List 传递      更新时间:2023-09-26


我想接受列表作为javascript函数的参数。
我从代码隐藏调用此函数。
并将一个列表传递给函数。
但是当函数调用时,我得到了"System.Collections.Generic.List'1[System.Int32]"作为参数的值。
调用函数时我应该怎么做才能获取列表。
我的代码是:
默认.aspx.cs

protected void Page_Load(object sender, EventArgs e)
    {
        List<int> num = new List<int> { 12, 13, 14, 15, 16, 17, 18 };
        List<int> oddNum = num.Where(n => n % 2 == 1).ToList();
        ScriptManager.RegisterStartupScript(this, GetType(), "test", "test('"+oddNum+"');", true);  
    }

默认.aspx

<head runat="server">
    <title></title>
    <script type="text/javascript">
        function test(oddNum) {
            alert(oddNum);
        }
    </script>
</head>

两个问题:

  1. 你依赖List<int>#ToString,它会给你一个字符串,如"System.Collections.Generic.List'1[System.Int32]"。您需要做一些事情来有效地输出列表。

  2. 你把它作为一个字符串传递给你的JavaScript函数。虽然这可以工作(我们可以在 JavaScript 中将其转换为数组),但没有必要;您可以直接将其作为数组传递。

在服务器上,使用 string.Join 将列表转换为字符串,并使用 [] 而不是'

ScriptManager.RegisterStartupScript(this, GetType(), "test", "test([" + string.Join(",",oddNum) + "]);", true);

假设我们的列表中有 1、3 和 5。这将像这样调用您的函数:

test([1, 3, 5]);

然后,您的 JavaScript 函数接收一个数组:

function test(oddNum) {
    // Use the oddNum array
}

尝试以下操作:

ScriptManager.RegisterStartupScript(this, GetType(), "test", "test('" + string.Join(",", oddNum) + "');", true);

String.Join(...) 方法将接受一个分隔符(在本例中为 ,)和一个列表,然后它将连接列表中的每个元素,使用分隔符将它们分开。