简体   繁体   English

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

[英]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. 现在,我想将此地图集成到我们的Web应用程序中,但是我无法使其正常工作。

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.) 编辑:在呈现页面的源代码中,javascript数组只是空的(所以我认为,markers1 / markers2字符串为空。)

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. 我将OSM与OpenLayers库配合使用来完成该任务。 If I use static values everything works fine. 如果我使用静态值,则一切正常。 But now I want to display markers that are in a SQL table. 但是现在我想显示SQL表中的标记。 What's the best way to get the data and fill it into the JS array? 获取数据并将其填充到JS数组中的最佳方法是什么?

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: 这是我的标记,其中包含将渲染地图的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>

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 [] . javascript数组格式在您的代码中必须为[[lat, lon], [lat, lon], [lat, lon]] ,格式为[lat, long], [lat, long],您在最后一个字符中,和丢失[]

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. 并在javascript中使用sampleFormat变量加载markers1。

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

And the same with the markers2. 与标记2相同。

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. 这里的问题是您没有将markers1和markers2解析为Javascript可以理解的JSON数组。

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 然后您要做的就是将字符串解析为json数组

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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