javascript - 如何从 C# 更新 javascript 变量数组

标签 javascript c# asp.net-mvc google-maps

我在标记的 javascript 中使用此数组来显示 map 中的所有标记,因为静态工作是完美的

 var markers = [
{
    "title": 'Aksa Beach',
    "lat": '31.6227697895779',
    "lng": '-4.998779296875',
    "description": '/www.google.com">Read more</a>'
}];

但是如果我可以在 html View 中添加模型中的一些标记就是我的问题

@foreach (var item in Model) {
    markers.push({
    "title": item.name,
    "lat": item.lat,
    "lng": item.long,
    "description": item.descript
});
}

最佳答案

用单引号或双引号将值括起来。也自 item是一个C#变量,需要使用@ 。您还需要使用<text>混合 C# 代码和纯文本(js 代码)时使用标签

<script>
  var markers = [];
  @foreach (var item in Model) {

   <text>
        markers.push({  "title": "@item.name",
                         "lat": "@item.lat",
                         "lng": "@item.long",
                         "description":"@item.descript"
                   });
   </text>

  }
</script>

关于javascript - 如何从 C# 更新 javascript 变量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39773245/

相关文章:

asp.net-mvc - Redis session 状态提供程序不会删除 session 放弃时的 key

javascript - 使用 length 属性获取事件目标时的困惑

c# - 为什么 Await 不会出现阻止对 EF 上下文的第二次操作

c# - 在 VS2017 中用 C# 打开 SQLite 数据库

html - ASP.NET Telerik 网格设计

javascript - 如何通过点击DataTable同一行的Edit按钮获取Id值

javascript - 检索当前日期之后的项目

javascript - 无法调用在 javascript 中声明的函数

java - JSP + JavaScript + Servlet 意想不到的结果

c# - SSIS脚本任务"Cannot execute script because the script entry point is invalid"错误