Jurate
Jurate

Reputation: 65

How can value in Javascript be accessed from C# code?

I'm trying to iterate through Model.DataList, however, I'm not able to get Javascript value 'i' in c#. Is it possible to access I from c#?

for (var i = 0; i < (@Model.DataList.Count); i++) {  
   var la = (@Model.DataList[i].Latitude)/1000000;
   var lo = (@Model.DataList[i].Longitude)/1000000;
   var marker = new google.maps.Marker({
      position: {lat: la, lng: lo},
      map: map,
      title: "Some title",
      zIndex: i
   });
}

Upvotes: 0

Views: 96

Answers (2)

kunal gaikwad
kunal gaikwad

Reputation: 110

try below approach may it will work for you

-script

var [email protected](Json.Encode(Model.SomeEnumerable));

for (var i = 0; i < list.length; i++) {  
   var la = list[i].Latitude/1000000;
  var lo = list[i].Longitude/1000000;
 var marker = new google.maps.Marker({
   position: {lat: la, lng: lo},
   map: map,
  title: "Some title",
  zIndex: i
 });}

Upvotes: 0

Satpal
Satpal

Reputation: 133403

If the above code is in View, You can use Json.Encode() Method converts a data object to a string that is in the JavaScript Object Notation (JSON) format.

var jsObject = @Html.Raw(Json.Encode(Model.DataList))

Then you can iterate it

for (var i = 0; i < jsObject.length; i++) {
    var la = (jsObject[i].Latitude) / 1000000;
    var lo = (jsObject[i].Longitude) / 1000000;
    var marker = new google.maps.Marker({
            position: {
                lat: la,
                lng: lo
            },
            map: map,
            title: "Some title",
            zIndex: i
        });
}

Upvotes: 2

Related Questions