在JavaScript中访问C#列表变量
本文关键字:列表 变量 访问 JavaScript | 更新日期: 2023-09-27 18:09:07
C#
public List<double> Coordinatesx = new List<Double>();
public List<double> Coordinatesy = new List<Double>();
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["TRY"].ConnectionString);
string query = "select x,y from Addresses";
cnn.Open();
SqlCommand cmd = new SqlCommand(query, cnn);
SqlDataReader id = cmd.ExecuteReader();
while(id.Read())
{
Coordinatesx.Add(Convert.ToDouble(id[0]));
Coordinatesy.Add(Convert.ToDouble(id[1]));
}
cnn.Close();
}
JAVASCRIPT
function calculateinside()
{
for (var j = 0; j < <%=Coordinatesx.Count%>; j++) {
var point = new google.maps.LatLng(<%=Coordinatesx%>[j],<%=Coordinatesy%>[j]);
if(google.maps.geometry.poly.containsLocation(point,poly)){
marker2 = new google.maps.Marker({
position: point,
map: map,
icon: 'images/point2.png',
});
}
}
} }
我正在尝试将变量从c#转换为javascript,我尝试过该代码,但出现了错误。
var point = new google.maps.LatLng(<%=Coordinatesx%>[j],<%=Coordinatesy%>[j]);
如何访问Coordinationsx和Coordinationsy列表的每个值?
您必须在javascript代码中生成数组:
function calculateinside()
{
var Coordinatesx = [<%=string.Join(",", Coordinatesx)%>];
var Coordinatesy = [<%=string.Join(",", Coordinatesy)%>];
for (var j = 0; j < Coordinatesx.lenght; j++) {
var point = new google.maps.LatLng(Coordinatesx[j],Coordinatesy[j]);
if(google.maps.geometry.poly.containsLocation(point,poly)){
marker2 = new google.maps.Marker({
position: point,
map: map,
icon: 'images/point2.png',
});
}
}
}
如果服务器端代码中有Coordinatesx = {1,2}
和Coordinatesy = {5,7}
,它将生成如下的javascript:
function calculateinside()
{
var Coordinatesx = [1,2];
var Coordinatesy = [5,7];
for (var j = 0; j < Coordinatesx.lenght; j++) {
var point = new google.maps.LatLng(Coordinatesx[j],Coordinatesy[j]);
if(google.maps.geometry.poly.containsLocation(point,poly)){
marker2 = new google.maps.Marker({
position: point,
map: map,
icon: 'images/point2.png',
});
}
}
}
您可以通过查看页面的html源代码来看到这一点。