1

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?

5
  • What is ViewBag.Retailers.Rows? Commented Dec 15, 2014 at 9:03
  • A "DataTable" sent from controller. Commented Dec 15, 2014 at 9:05
  • I know this might be silly, but have you tried to remove the ; from the lat and long props? Commented Dec 15, 2014 at 9:09
  • 3
    Add the values as data-* attributes to the table row in the loop, then use one script at the end to build the array and avoid duplicating this script and rendering unnecessary html. Commented Dec 15, 2014 at 9:22
  • @StephenMuecke Would you please post an example? Commented Dec 15, 2014 at 9:38

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.