将c#datatable传递到javascript多维数组列表中
本文关键字:数组 列表 javascript c#datatable | 更新日期: 2023-09-27 18:29:59
我需要以以下格式将数据表从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);
}
}
请帮我渡过难关。提前谢谢。
基本上,您要查找的是JSON,而不是javascript数组。
您可以使用JavaScriptSerializer
类:
using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);
我还建议您对这种类型的请求使用web方法或通用http处理程序。