rdans
rdans

Reputation: 2157

Collection iteration in javascript using inline server tags

I have an asp.net user control which exposes a public IEnumerable object. This could be converted to a list or array if it helps to answer the question. What I would like to do is to loop through all of the server objects within a javascript function and do something with the contents of each item. I would like to achieve this using inline server tags if possible. Something like the below.

function iterateServerCollection()
{
    foreach(<%=PublicCollection %>)
    {
        var somevalue = <%=PublicCollection.Current.SomeValue %>;
    }
}

Is it possible to achieve this?

Upvotes: 0

Views: 190

Answers (2)

rdans
rdans

Reputation: 2157

Managed to achieve what I wanted thanks to the comment from geedubb. Here's what the working javascript looks like.

var myCollection = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myCollection) %>;

for(var i in myCollection)
{
    var somevalue = myCollection[i].SomeValue;
}

Upvotes: 1

Daniel Dawes
Daniel Dawes

Reputation: 1005

I would do as others have suggested and serialize the object, you could even use an ajax call to grab the data from the start of that function

function iterateServerCollection()
{

    //Ajax call to get data from server HttpHandler/WebAPI/Service etc.

    for(var item in resultObject) {
        //you can use item.WhateverPropertyIsOnObject
    }
}

Upvotes: 0

Related Questions