Bou Rif Abdou Bou Rif Abdou - 2 months ago 7
C# Question

how to update javascript variable array from c#

am working with this array in javascript of marks to show all marks in the map as static work is perfect

var markers = [
{
"title": 'Aksa Beach',
"lat": '31.6227697895779',
"lng": '-4.998779296875',
"description": '/www.google.com">Read more</a>'
}];


but if i can add some marks from model in html view is my problem

@foreach (var item in Model) {
markers.push({
"title": item.name,
"lat": item.lat,
"lng": item.long,
"description": item.descript
});
}

Answer

Wrap the values with single or double quotes. Also since item is a C# variable, you need to use @. You also need to use <text> tag as you are mixing C# code and plain text (js code)

<script>
  var markers = [];
  @foreach (var item in Model) {

   <text>
        markers.push({  "title": "@item.name",
                         "lat": "@item.lat",
                         "lng": "@item.long",
                         "description":"@item.descript"
                   });
   </text>

  }
</script>
Comments