将c#datatable传递给javascript多维数组列表

时间:2014-11-10 04:42:07

标签: javascript c# asp.net

我需要以下列格式将asp.net c#中的数据表传递给java脚本。

var markers = [
{
    "title": 'Campbell Donald',
    "lat": '35.821201',
    "lng": '-78.703884',
    "description": '3100 Blue Ridge Rd,Raleigh,NC,27612'
},
{
    "title": 'Hoffman Byron',
    "lat": '35.723053',
    "lng": '101.7061447',
    "description": '421 N Holly Ave,Siler City,NC,27344'
},
{
    "title": 'Jalan Intan (Gombak)',
    "lat": '3.22317',
    "lng": '101.71588',
    "description": 'Jalan Intan (Gombak), Kuala Lumpur, Wilayah Persekutuan Kuala Lumpur, 53100'
},
{
    "title": 'Jalan Madrasah',
    "lat": '3.218515',
    "lng": '101.717801',
    "description": 'Jalan Madrasah, Kuala Lumpur, Wilayah Persekutuan Kuala Lumpur, 53100'
}

];

我尝试用我的代码以这种方式分配标记变量。

DataTable dthcp = dbUtil.getHcpbyMapdistance();

    var serializer = new JavaScriptSerializer();
    StringBuilder sb = new StringBuilder();
    sb.Append("<script>");
    sb.Append("var markers = [];");
    foreach (object dataRow in dthcp.Rows)
    {
        sb.Append("markers.push('" + string.Format("var jsArray = {0}", serializer.Serialize(dataRow)) + "');");
    }
    sb.Append("</script>");
    ClientScript.RegisterStartupScript(this.GetType(), "TestArrayScript", sb.ToString(),true);

我的java脚本部分

var markers = [];

window.onload = function () {

    var mapOptions = {
        center: new google.maps.LatLng(markers[1].lat, markers[1].lng),
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);

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

    for (i = 1; i <= markers.length; i++) {
        var data = markers[i - 1]
        var myLatlng = new google.maps.LatLng(data.lat, data.lng);

        var marker = new MarkerWithLabel({
            position: myLatlng,
            map: map,
            title: data.title,
            labelContent: i,
            labelAnchor: new google.maps.Point(6, 34),
            labelClass: "labels", // the CSS class for the label
            labelInBackground: false
        });

        (function (marker, data) {
            google.maps.event.addListener(marker, "click", function (e) {
                infoWindow.setContent(data.description);
                infoWindow.open(map, marker);
            });
        })(marker, data);

    }
}

请帮我解决这个问题。提前谢谢。

1 个答案:

答案 0 :(得分:0)

基本上你正在寻找JSON而不是javascript数组。

您可以使用JavaScriptSerializer类:

using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);

我还建议您使用web-methodgeneric http handler来处理此类请求。