0

I am trying to write a simple for in JS which uses an element from a list declared in C# code behind. Actually there is a problem here: ['i'] - compiler doesn't know what is i.

How can I write this for properly?

for (var i = 0; i < '<%= poz.Count %>'; i++) {
    var Latitude = '<%= poz['i'].Latitude %>';
}

3 Answers 3

2

your counter variable is not defined in your c# code. It is a javascript variable.

If you want the values of your poz object to be available to javascript you need to write them out to some javascript structure with a loop written in c#.

Sign up to request clarification or add additional context in comments.

Comments

2

You have got this upside down. The C# must put all data in the HTML page for the JavaScript to get. Unless you provide an API, there is no way for the JS to get the data.

I suggest the following C# pseudocode that produces JavaScript in the HTML (note this is not perfect C#).

function myJsFunction()
{
    var jsLattitudes = {};
    <%
    int i;
    for(i = 0; i < lattitudes.Length)
    {
        document.WriteLn(string.Format("jsLattitudes[{0}] = '{1}';\r\n", i, lattitues[i].Lattitude));
    }
    %>
}

Comments

0

You could do something like this

var locations = [ { <%= string.Join("},\n{",
                        locations.Select(l => string.Format("Longitude: {0}, Latitude: {1}",
                        l.Longitude.ToString(),
                        l.Latitude.ToString()))) %> } ]

for (var i = 0; i < locations.length; i++) {
    var Longitude = locations[i].Longitude;
    var Latitude = locations[i].Latitude;
}

This assumes that you have a class like

public class Location
{
    public int Longitude { get; set; }
    public int Latitude { get; set; }
}

and locations is IEnumerable may be like this

var locations = new List<Location> {
    new Location { Longitude = 10, Latitude = 20 },
    new Location { Longitude = 11, Latitude = 21 },
    new Location { Longitude = 12, Latitude = 22 }
};

Comments

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.