remondo Posted September 18, 2006 Posted September 18, 2006 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. Quote
Gill Bates Posted September 22, 2006 Posted September 22, 2006 Here's the best way to do it: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: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:['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:[{id:1,name:'pedro'},{id:2,name:'david'}]This could by accessed on the client like:alert(myList[1].name); Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.