Reputation: 7291
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
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
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