简体   繁体   中英

Pass string data from C# to JS

After I solved this problem , everything worked fine, while testing on my localhost. Now I want to integrate this map into our web application but I just can't get it to work.

EDIT: In the source code of the rendered page the javascript array is just empty (so I assume, that the markers1 / markers2 strings are empty.)

From my other question:

I want to display a map that shows an array of markers. I'm using OSM with the OpenLayers Library to accomplish that. If I use static values everything works fine. But now I want to display markers that are in a SQL table. What's the best way to get the data and fill it into the JS array?

Here's my code:

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();
        }

    }
}

And this is my markup inculding the js that will render the map:

<%@ 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>

Any ideas why this doesn't work? Thanks in advance!

May be this can help you:

The javascript array format must be [[lat, lon], [lat, lon], [lat, lon]] in your code the format is [lat, long], [lat, long], you have in the last char , and missing [] .

Try the following code:

        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();

And in the javascript use the sampleFormat variable to load in markers1.

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

And the same with the markers2.

I would also like indicaras me more details about your error.

Sorry for my english, I hope help you.

The issue here is that you do not parse your markers1 and markers2 into a JSON array that Javascript can understand.

Try

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

NOTE the inverted commas around the [].

And then all you have to do is Parse the strings to json array

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM