简体   繁体   English

在MVC Razor foreach循环中编写JavaScript代码

[英]Write JavaScript code in MVC Razor foreach loop

I would like to embed javascript code in razor code. 我想将javascript代码嵌入剃须刀代码中。 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: 使用JavaScript混用剃须刀,你需要在单引号剃刀代码'是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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