user1220099
user1220099

Reputation: 127

How to build javascript array for google map coordinates using MVC Model

I'm trying to build an array using the data from an MVC Model

    var locations = [];

I'm trying to loop through the Model and build the array like this:

     @{var count = 0; }
    @foreach (var item in Model.Locations)
    {
    locations[count] = new locations[@item.StreetAddress, @item.Latitude, @item.Longitude, count+1];
    count++;
    }

Any ideas on how to get this done?

Upvotes: 0

Views: 93

Answers (2)

Dandy
Dandy

Reputation: 2177

Try

var locations = @Html.Raw(Json.Encode(Model.Locations));

Upvotes: 1

code
code

Reputation: 1137

If I understand correctly you are trying to loop through each item and add to array? Why not just cast your list to an array? I'm assuming your Model.Locations is a list of Location

var locations = Model.Locations.ToArray();

There your list is cast to an array in 1 line. If your Model.Locations is not a list or you want to step through each item one by one for other reasons :

@{var count = 0; }
@foreach (var item in Model.Locations)
{
    locations[Model.Locations.IndexOf(item)] = new location[@item.StreetAddress, @item.Latitude, @item.Longitude, count+1];
    count++;
}

Upvotes: 0

Related Questions