【发布时间】:2019-04-04 15:22:39
【问题描述】:
我创建了一个数组并将其传递给 ViewBag。
ViewBag.MarkerList = Utility.markerList;
我有一个函数可以在 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);
如何在 ViewBag 中使用 foreach 并调用 JavaScript 函数?
【问题讨论】:
-
你想在哪里调用这个函数?在页面加载或按钮/链接点击?
-
Razor 不执行 JavaScript。 Razor(可能)输出浏览器最终运行的 JavaScript。
-
@Pio 在页面加载中
-
@ARM4N8 当您在浏览器中单击“查看页面源代码”时,您的 JavaScript 是什么样的?这可能会给你一个线索。
-
将 markerList 预格式化为字符串,并放入 ViewBag。我假设你有
List<string>。所以 ac ode 看起来像这样:List<string> l = new List<string> { "Saab", "Volvo", "BMW" }; string strOutput = "["; l.ForEach(x => strOutput += String.Format("\"{0}\",", x)); strOutput = strOutput.Substring(0, strOutput.Length - 1); strOutput += "]"; ViewBag.MarkerList = strOutput;
标签: javascript c# razor model-view-controller