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

时间:2015-03-16 09:34:56

标签: javascript c# asp.net


我想接受List作为javascript函数的参数 我从后面的代码中调用这个函数 并将一个List传递给函数。
但我得到了&#34; System.Collections.Generic.List`1 [System.Int32]&#34;作为函数调用时的参数值。
当调用函数时,我该怎么做才能获得列表 我的代码是:
Default.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);  
    }

的Default.aspx

<head runat="server">
    <title></title>
    <script type="text/javascript">

        function test(oddNum) {
            alert(oddNum);
        }
    </script>
</head>

2 个答案:

答案 0 :(得分:2)

两个问题:

  1. 您依赖于List<int>#ToString,它会为您提供类似“System.Collections.Generic.List`1 [System.Int32]”的字符串。您需要做一些事情来有效地输出列表。

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

  3. 在服务器上,使用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
    }
    

答案 1 :(得分:1)

尝试以下方法:

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

String.Join(...)方法将接受一个分隔符(在这种情况下它是,)和一个List,它将连接列表中的每个元素,使用它们分隔它们分隔符。

相关问题