将字符串数据从C#传递给JS

时间:2014-10-16 11:19:32

标签: javascript c# asp.net openlayers

在我解决this problem后,一切正常,同时在我的localhost上进行测试。现在我想将这个地图集成到我们的网络应用程序中,但我无法让它工作。

修改: 在渲染页面的源代码中,javascript数组只是空的(所以我假设,markers1 / markers2字符串是空的。)

从我的另一个问题:

  

我想显示一个显示标记数组的地图。我正在使用OSM   使用OpenLayers Library来实现这一目标。如果我使用静态值   一切正常。但现在我想显示一个标记   SQL表。什么是获取数据并将其填入JS的最佳方式   阵列

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Text;


public partial class fibre : System.Web.UI.Page
{
    protected string markers1;
    protected string markers2;

    public void Page_Load(object sender, EventArgs e)
    {

        // Construct the connection string to interface with the SQL Server Database
        string connStr = @"Data Source=CHRISTIANHP\SQLEXPRESS;Initial Catalog='C:\PROGRAM FILES (X86)\MICROSOFT SQL SERVER\MSSQL12.SQLEXPRESS\MSSQL\DATA\FUSIONCHARTSDB.MDF';Integrated Security=True";

        // Initialize the strings which contain the map data
        StringBuilder markerStr1 = new StringBuilder();
        StringBuilder markerStr2 = new StringBuilder();

        // Create a SQLConnection object 
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            // Establish the connection with the database
            conn.Open();

            // Construct and execute SQL queries which would return the map data
            SqlCommand query1 = new SqlCommand("SELECT t.lat, t.lon FROM (SELECT T_Fibre.lat, lon, ROW_NUMBER() OVER (ORDER BY lat) AS rownum FROM t_Fibre) AS t WHERE t.rownum % 10 = 0 ORDER BY t.lon", conn);
            SqlCommand query2 = new SqlCommand("SELECT t.lat, t.lon FROM (SELECT T_FibreReady.lat, lon, ROW_NUMBER() OVER (ORDER BY lat) AS rownum FROM T_FibreReady) AS t WHERE t.rownum % 10 = 0 ORDER BY t.lon", conn);

            // Begin iterating through the result set (1)
            SqlDataReader rst1 = query1.ExecuteReader();

            while (rst1.Read())
            {
                // Construct the marker data
                markerStr1.AppendFormat("[{0}, {1}], ", rst1["lat"].ToString(), rst1["lon"].ToString());
            }

            // Close the result set Reader object
            rst1.Close();

            // Begin iterating through the result set (2)
            SqlDataReader rst2 = query2.ExecuteReader();

            while (rst2.Read())
            {
                // Construct the marker data
                markerStr2.AppendFormat("[{0}, {1}], ", rst2["lat"].ToString(), rst2["lon"].ToString());
            }

            // Close the result set Reader object
            rst2.Close();

            // Close the Connecton object
            conn.Close();

            // Convert data into string and pass it to the markers variables
            markers1 = markerStr1.ToString();
            markers2 = markerStr2.ToString();
        }

    }
}

这是我的标记,其中包含将渲染地图的js:

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="fibre.aspx.cs" Inherits="fibre" %>

<asp:Content ID="cntChart" ContentPlaceHolderID="CPH_visual1" Runat="Server">
    <asp:Literal  ID="Literalsingle" runat="server"></asp:Literal>
    <div id="mapdiv" style="height: 100%; position: relative;">
       <!-- map will render here! -->
    </div>

    <!-- map built with OpenLayers api on OpenStreetMap -->
    <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
    <script>
        map = new OpenLayers.Map("mapdiv");
        map.addLayer(new OpenLayers.Layer.OSM());

        epsg4326 = new OpenLayers.Projection("EPSG:4326"); // WGS 1984 projection
        projectTo = map.getProjectionObject(); // The map projection (Spherical Mercator)

        // Define center-point
        var lonLat = new OpenLayers.LonLat(8.2891666666666666666666666, 46.8344444444444444444).transform(epsg4326, projectTo);

        map.setCenter(lonLat, 1);

        var vectorLayer = new OpenLayers.Layer.Vector("Overlay");

        // Pass map data from C# string to JS array
        var markers1 = [ <%=markers1%>];
        var markers2 = [ <%=markers2%>];

        // Loop through the markers2 array and create markers
        for (var i = 0; i < markers2.length; i++) {

            var lon = markers2[i][1];
            var lat = markers2[i][0];

            var feature = new OpenLayers.Feature.Vector(
                    new OpenLayers.Geometry.Point(lon, lat).transform(epsg4326, projectTo),
                    { description: "marker number " + i },
                    { externalGraphic: 'Pictures/marker_r.jpg', graphicHeight: 8, graphicWidth: 8, }
                );
            vectorLayer.addFeatures(feature);
        }


        //Loop through the markers1 array and create markers
        for (var i = 0; i < markers1.length; i++) {

            var lon = markers1[i][1];
            var lat = markers1[i][0];

            var feature = new OpenLayers.Feature.Vector(
                    new OpenLayers.Geometry.Point(lon, lat).transform(epsg4326, projectTo),
                    { description: "marker number " + i },
                    { externalGraphic: 'Pictures/marker_r.jpg', graphicHeight: 8, graphicWidth: 8, }
                );
            vectorLayer.addFeatures(feature);
        }

        map.addLayer(vectorLayer);
    </script>
</asp:Content>

为什么这不起作用的任何想法?提前谢谢!

2 个答案:

答案 0 :(得分:0)

可能这可以帮到你:

您的代码中的javascript数组格式必须为[[lat, lon], [lat, lon], [lat, lon]],格式为[lat, long], [lat, long],,您在上一个字符,中的格式为[],但缺少 while (rst2.Read()) { // Construct the marker data markerStr2.AppendFormat("[{0}, {1}], ", rst2["lat"].ToString(), rst2["lon"].ToString()); } //SAMPLE CODE string sampleFormat = markerStr2.ToString(); if (sampleFormat.EndsWith(",")) { sampleFormat = sampleFormat.Substring(0, sampleFormat.Length - 2); } sampleFormat = string.Format("[{0}]", sampleFormat); // Close the result set Reader object rst2.Close();

请尝试以下代码:

  var markers1 = [ <%=sampleFormat%>];

在javascript中使用sampleFormat变量加载markers1。

{{1}}

与标记2相同。

我还想告诉我有关你的错误的更多细节。

对不起我的英语,我希望能帮到你。

答案 1 :(得分:0)

这里的问题是你没有将你的markers1和markers2解析为Javascript可以理解的JSON数组。

尝试

var markers1AsString = '[ <%=markers1%>]';
var markers2AsString = '[ <%=markers2%>]';

注意[]。

周围的引号

然后您需要做的就是将字符串解析为json数组

var markers1 = JSON.parse(markers1AsString);
var markers2 = JSON.parse(markers2AsString);

for (var i = 0; i < markers2.length; i++) {
  // bla bla
}