s.k.paul
s.k.paul

Reputation: 7291

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?

Upvotes: 1

Views: 2693

Answers (2)

user3559349
user3559349

Reputation:

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

Upvotes: 3

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

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>

Upvotes: 3

Related Questions