【问题标题】:Access to a C# object in a Javascript script访问 Javascript 脚本中的 C# 对象
【发布时间】:2019-02-14 22:13:13
【问题描述】:

我在一个 C# 项目中工作。在一个视图中,我需要使用我的老师提供的脚本(在 Javascript 中)。 首先,我的视图收到一个列表。例如:[位置 1,位置 2,位置 3]。位置具有纬度和经度参数。 在我的 Javascript 中,我有函数“L.marker([x,y]).addTo(mapa).on('click', onClick);”。我想要的是通过 location1.longitude 和 location1.latitude 作为标记函数的参数。我该怎么做?

@model List<SistemaGestion.Helpers.JsonApiGoogle.Location>

(some HTML code)

<script>
(code)
       for (var coordenadas in Model) {
            L.marker([coordenadas.latitude, coordenadas.longitude]).addTo(mapa).on('click', onClick);
        }
</script>

【问题讨论】:

  • 您可以使用 json.net/newtonsoft 之类的东西将您的 c# 对象字符串化到您的脚本标签中。
  • 你能详细解释一下吗? ....

标签: javascript c# html model-view-controller


【解决方案1】:

这是一个如何序列化为 JSON 的简单示例。为简单起见,我将用一个简单的字符串列表替换您的对象列表。但它应该适用于几乎任何数据结构(有一些注意事项,例如递归嵌套)

@using System.Collections.Generic
@using Newtonsoft.Json
@model List<string>

@{ // this is running server-side
    var json = JsonConvert.SerializeObject(Model); 
}

<script> // this will run client-side, 
    //but the @Html.Raw(json) will be "injecting" into the client side script.
    var array = @Html.Raw(json); 
    console.log(array);
</script>

Html.Raw 很重要,否则它会转义“作为”之类的东西。

如果您在浏览器中查看源代码会是什么样子:

var array = ["hello","world","this","is","a","test"];

【讨论】:

    猜你喜欢
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多