0

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
   });
}
3
  • you can do like ViewBag.Count = Model.DataList.Count in C# and then in your.cshrml use @ViewBag.Count Commented Sep 7, 2017 at 9:47
  • @Fran, I think dupe vote is incorrect as OP is trying to access razor value, not trying to pass Commented Sep 7, 2017 at 10:00
  • 1
    @Satpal I retracted my duplicate vote when I saw your answer and voted it up too :) But because others voted too the comment is still visible. I'm sure there is a duplicate for it as using Html.Raw(Json(....)) is a common solution to this question. I will delete the dup comment as well. Commented Sep 7, 2017 at 10:42

2 Answers 2

2

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
        });
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
 });}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.