简体   繁体   中英

How to call JavaScript function in Razor

I've created an array and pass it to view with ViewBag.

ViewBag.MarkerList = Utility.markerList; 

And I have a function to add a marker on map in JavaScript:

function myFunction(item) {
    var marker = L.marker([item.lat, item.lng], { riseOnHover: true }).addTo(mymap);
    marker.bindPopup("I am a popup.<br>"+ item.lat + "," + item.lng);
}
var array = @ViewBag.MarkerList;

        array.foreach(myFunction);

How can I use foreach in ViewBag and call the JavaScript function?

You can convert c# array to json for javascript in method and call method on page load.

function myFunction() {
    var markerList= @Html.Raw(Json.Serialize(ViewBag.MarkerList));
    for(item in markerList) {
        var marker = L.marker([item.lat, item.lng], { riseOnHover: true}).addTo(mymap);
        marker.bindPopup("I am a popup.<br>"+ item.lat + "," + item.lng);
    }
}

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