将列表项从 C# 传递到 javascript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11826936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:24:17  来源:igfitidea点击:

pass list item from c# to javascript array

c#javascriptarrayslist

提问by rahularyansharma

I have following code to show multiple marker on gmap

我有以下代码在 gmap 上显示多个标记

<script type="text/javascript">

        function init() {
            var locations = [
              ['Bondi Beach', -33.890542, 151.274856, 4],
              ['Coogee Beach', -33.923036, 151.259052, 5],
              ['Cronulla Beach', -34.028249, 151.157507, 3],
              ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
              ['Maroubra Beach', -33.950198, 151.259302, 1]
            ];

            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 10,
                center: new google.maps.LatLng(-33.92, 151.25),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            var infowindow = new google.maps.InfoWindow();

            var marker, i;

            for (i = 0; i < locations.length; i++) {
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                    map: map
                });

                google.maps.event.addListener(marker, 'click', (function (marker, i) {
                    return function () {
                        infowindow.setContent(locations[i][0]);
                        infowindow.open(map, marker);
                    }
                })(marker, i));
            }
            return false;
        }
    </script>

I want to make this dynamic so i have to pass this

我想让这个动态,所以我必须通过这个

 var locations = [
              ['Bondi Beach', -33.890542, 151.274856, 4],
              ['Coogee Beach', -33.923036, 151.259052, 5],
              ['Cronulla Beach', -34.028249, 151.157507, 3],
              ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
              ['Maroubra Beach', -33.950198, 151.259302, 1]
            ];

from c# code to this js .

从 c# 代码到这个 js 。

I have tried Hidden Field and this code

我已经尝试过隐藏字段和这段代码

 List<String> oGeocodeList = new List<String>
                                         {
                                            "'Bondi Beach', -33.890542, 151.274856, 4",
                                            "'Coogee Beach', -33.923036, 151.259052, 5",
                                            "'Cronulla Beach', -34.028249, 151.157507, 3",
                                            "'Manly Beach', -33.80010128657071, 151.28747820854187, 2",
                                            "'Maroubra Beach', -33.950198, 151.259302, 1"
                                        };

        var geocodevalues = string.Join(",", oGeocodeList.ToArray());
        ClientScript.RegisterArrayDeclaration("locations", geocodevalues);

But NO luck any reference will be helpful to me

但运气不好,任何参考资料都会对我有帮助

采纳答案by L.B

Using Json.Net

使用Json.Net

var obj = new[] { 
    new object[] { "Bondi Beach", -33.890542, 151.274856, 4 },
    new object[] { "Coogee Beach", -33.923036, 151.259052, 5 },
    new object[] { "Cronulla Beach", -34.028249, 151.157507, 3 },
    new object[] { "Manly Beach", -33.80010128657071, 151.28747820854187, 2 },
    new object[] { "Maroubra Beach", -33.950198, 151.259302, 1 },
};
var json = JsonConvert.SerializeObject(obj);

回答by Liam

I would encode the C# into Json using Json.Netor the C# Json encoder. Then write it into the hidden field. Then decode it on the JavaScript side using Json2

我会使用Json.Net或 C# Json 编码器将 C# 编码为 Json。然后将其写入隐藏字段。然后在 JavaScript 端使用Json2 解码

回答by Richard

Essentially what I believe you're trying to do is create a JSONstring. JSONallows you to pass objects in a serialized string format between many languages, including JavaScript and C#. I'd recommend taking a look at the JSON .NET library. It's a fantastic library that will allow you to safely and effeciently serialize items to-and-from strings in C#.

基本上我相信你要做的是创建一个JSON字符串。JSON允许您在多种语言(包括 JavaScript 和 C#)之间以序列化字符串格式传递对象。我建议看看JSON .NET 库。这是一个很棒的库,它允许您在 C# 中安全有效地序列化项目到和从字符串。

I'd also recommend, instead of passing a multi-dimensional array, that you create a more OOP structure. To do this you'll want to create a class for your locations, I'm going to assume the following:

我还建议您创建一个更面向对象的结构,而不是传递多维数组。为此,您需要为您的位置创建一个类,我将假设以下内容:

public class Location
{
    public string Name { get; set; }
    public double Lat { get; set; }
    public double Lng { get; set; }
}

You'll then want to construct a List<Location>, and then serialize that using the JSON .NET library, which will be as easy as this:

然后,您需要构造一个List<Location>,然后使用 JSON .NET 库对其进行序列化,这将非常简单:

List<Location> oGeocodeList = new List<Location>() {
    //...
};

string json = JsonConvert.SerializeObject(oGeocodeList);

With this JSON, you'll either want to write it to a hidden field, or to a variable within the JavaScript. This will then allow you to reference it on your page through the JavaScript. There is also pretty comprehensive documentation, which proves very useful!

使用此 JSON,您要么希望将其写入隐藏字段,要么写入 JavaScript 中的变量。这将允许您通过 JavaScript 在您的页面上引用它。还有非常全面的文档,证明非常有用!

This can then be accessed in your JavaScript as any other js object, like so:

然后可以在您的 JavaScript 中像任何其他 js 对象一样访问它,如下所示:

for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i].Lat, locations[i].Lng),
        map: map
    });

    // ...
}

回答by Moons

I think what you can do is create a List.

我认为您可以做的是创建一个列表。

Example:

例子:

List<T> data = new List<T>();

System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

return serializer.Serialize(data);

Thats it.

就是这样。

I hope it work

我希望它有效

回答by Abbas Dehghan

you must use it something like this: in your controller:

你必须像这样使用它:在你的控制器中:

 var locations = [
          ['Bondi Beach', -33.890542, 151.274856, 4],
          ['Coogee Beach', -33.923036, 151.259052, 5],
          ['Cronulla Beach', -34.028249, 151.157507, 3],
          ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
          ['Maroubra Beach', -33.950198, 151.259302, 1]
        ];
var locationsString = JsonConvert.SerializeObject(locations);
ViewBag.locationsString = locationsString;
return View();

and in your java script use it like this:

并在您的 Java 脚本中像这样使用它:

var data = JSON.parse(@ViewBag.locationsString);

and you can have your data in array and use it in javascript each function:

您可以将数据放在数组中,并在 javascript 中的每个函数中使用它:

$.each(data, function (i, item) {
//enter your code
}

for javascript not jquery use:

对于 javascript 而不是 jquery 使用:

for (var i = 0; i < data.length; i++) {
       addMarker(data[i], map);
    }