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>
Two issues:
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.
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
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.