简体   繁体   中英

Write JavaScript code in MVC Razor foreach loop

I would like to embed javascript code in razor code. I've tried the following-

   <tbody>
        @foreach (var row in ViewBag.Retailers.Rows) //Retailers is a datatable
        {
            <tr>
                <td>@row["RegionName"].ToString()</td>
            </tr>
            <script>
                  var marker=new Object();
                  marker.lat=@row["Latitude"].ToString();
                  marker.lon=@row["Longitude"].ToString();
                  markersArray.push(marker);
           </script>
        }

   </tbody>

But, it's not working. Any help?

To mix razor with JavaScript, you need to include razor code in single quotes ' like this:

        <script>
              var marker=new Object();
              marker.lat='@row["Latitude"].ToString()';
              marker.lon='@row["Longitude"].ToString()';
              markersArray.push(marker);
       </script>

I would recommend you avoid generating all these inline scripts and instead add the values as data attributes of the row

<tbody id="retailers">
  @foreach (var row in ViewBag.Retailers.Rows) //Retailers is a datatable
  {
    <tr data-latitude="@row["Latitude"]" data-longitude="@row["Longitude"]">
      <td>@row["RegionName"].ToString()</td>
    </tr>
  }
</tbody>

then have a single script to build your array

var markersArray = [];
$('#retailers tr').each(function() {
  markersArray.push({ lat: $(this).data('latitude'), lon: $(this).data('longitude') });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM