Accessing generic list element from ASP .Net from Javascript

remondo

Newcomer
Joined
Sep 9, 2006
Messages
3
Hi everybody, please help...

So here's the scenario, I have populated a Generic List with strings from an SQL Select Command.

Then using Javascript, i want to retrieve certain elements from the Generic List variable. In server side, you can access the List in a syntax like this:

stringvariable = mylist.Item(5) '5 is the element number

In Javascript, you can access variables (not list types or array types) in something like this

var jvar = <%= aspvar %> 'where aspvar is an asp .net variable

I have tried retrieving an element from an asp .net in some code like this:

var jvar = <%= mylist.Item(5) %>

this works just fine. But of course, i want to be able to control which element i want to retrieve. I don't want to retrieve the 6th element all the time :-). The problem with the code above is that it doesn't recognize Javascript variables inside the <% %> tags. So if there could be ways to put in Javascript variables inside the <% %> tags then I could now control it perfectly.
 
Here's the best way to do it:
C#:
foreach (MyClass m in myList)
{
    builder.Append(m.ToString());
    builder.Append(",");
}

Response.Write(string.Format("<script>var myList = [{0}];</script>", builder.ToString().TrimEnd(',')));
Then, in javascript, you can access an element in the list by its corresponding index:
Code:
var jvar = myList[5];
I should note that if the ToString() method returns a string then it needs to be wrapped in quotes, so as to generate a list like:
Code:
['a','b','c']
If you need to represent a complex object then you will need to return a literal object as a string, so as to generate:
Code:
[{id:1,name:'pedro'},{id:2,name:'david'}]
This could by accessed on the client like:
Code:
alert(myList[1].name);
 
Back
Top