0


I want to accept List as argument of javascript function.
I am calling this function from code behind.
And passing one List to the function.
But i got "System.Collections.Generic.List`1[System.Int32]" as value of argument when function called.
What should i do to get list when function called.
My code is:
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 Answers 2

2

Two issues:

  1. You're relying on List<int>#ToString, which will give you a string like "System.Collections.Generic.List`1[System.Int32]". You need to do something to output the list usefully.

  2. You're passing it to your JavaScript function as a string. While that can work (we could convert it to an array in JavaScript), there's no need; you can pass it directly as an array.

On the server, convert the list to a string using string.Join and use [ and ] instead of ' around it:

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

Say our list has 1, 3, and 5 in it. That calls your function like this:

test([1, 3, 5]);

Your JavaScript function then receives an array:

function test(oddNum) {
    // Use the oddNum array
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ya its useful.. I got the result without manually separate result by ','. Thanks.
1

Try the following:

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

The String.Join(...) method will take in a delimiter (in this case it's ,) and a List, it will then concatenate every element in the list, separating them using the delimiter.

1 Comment

Thanks... I got the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.