Transferring string information from C# to JavaScript

After successfully resolving an issue on my localhost following this particular problem, I encountered difficulties when attempting to integrate the map into our web application.

EDIT: The javascript array appears empty in the source code of the rendered page (indicating that the markers1 / markers2 strings are also empty).

Continuing from a previous inquiry:

I am aiming to showcase a map populated with an array of markers using OSM and the OpenLayers Library. While static values function without issues, the challenge arises when trying to display SQL table-based markers. What is the optimal method for extracting data and populating it within the JS array?

Below is the provided code snippet:

inclined towards reaching

In addition to my code, here is the markup containing the necessary JavaScript to 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>
        // JS script content goes here
    </script>
</asp:Content>

Any insights on why this setup might be failing? Your assistance is much appreciated!

Answer №1

Perhaps this information could be beneficial to you:

In order for the javascript array format to work correctly, it should be structured as

[[lat, lon], [lat, lon], [lat, lon]]
. However, in your current code, the format appears as [lat, long], [lat, long],, with an extra comma at the end and missing square brackets [].

You can try using the following code snippet:

        while (rst2.Read())
        {
            // Build 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();

Then, in the javascript section, utilize the sampleFormat variable to load in markers1.

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

Repeat the same process for markers2.

If possible, please provide more details regarding the error you are encountering.

I apologize for any language barriers, but I hope this information proves helpful to you.

Answer №2

The problem lies in your failure to convert markers1 and markers2 into a format that can be understood by JavaScript.

Give this a try:

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

Make sure to include the quotation marks around the [].

Then, simply parse the strings into JSON arrays like so:

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Best practice for handling asynchronous calls in Monotouch

Imagine having an asynchronous call in your Monotouch project that looks like this: context.getNameCompleted += HandleContextgetNameCompleted; context.getNameAsync(); void HandleContextgetNameCompleted(object sender, getNameCompletedEventArgs args) { ...

Is there a way to access the pixel data of a scene in Three.js without having to render it on the canvas?

Is there a way to obtain the pixel data (in the form of an array buffer) that would be displayed on a canvas if I were to render a scene, without actually rendering it on the canvas? If so, how can this be achieved? I have not written any code for this ye ...

Activating the Play button to start streaming a link

Recently delved into the world of Ionic 4 and Angular, so definitely a beginner :) Purchased a UI Template from code canyon but didn't realize I needed to code the music player part. Been trying to get a music stream playing but no luck. Came across ...

Display or conceal a division underneath a dropdown menu based on selections retrieved from a SQL Server database

Presented here is my JavaScript code. function appendItemforPurchaseOrder() { debugger var rowNumber = parseInt($(".itemmapContainer").attr("data-rownumber")); rowNumber = isNaN(rowNumber) ? 1 : rowNumber + 1; var addNewItemDetailHtml = ...

Obtain data from handlebars within a script tag

Is it possible to retrieve a handlebar parameter inside a script tag within a handlebars template? <script> var myList = {{list}} </script> This particular template is invoked from express using the following: response.render('t ...

Developing perforations in three.js

This excerpt was sourced from a discussion on adding holes to rendered shapes in Three.js, as seen at THREEJS: add hole to rendered Shape. Despite trying the provided code, it is still not functioning as expected. The encountered error message reads: t ...

Is there a way for me to provide the product ID based on the selected product?

Is there a way to store the IDs of selected products in a dynamic form with multiple product options? I am able to see the saved products in the console.log(fields, "fields");, but how can I also save the selected product IDs? Any guidance on th ...

Guide for adding multiple markers on a Google map

Currently, I am facing a challenge with plotting multiple markers on a Google map and need some assistance. The longitude and latitude of the locations are extracted from JSON data obtained through an AJAX API call. I have been referring to a particular p ...

Visualize data retrieved from a third-party website through scraping in a chart

After attempting to extract data from a website's data.asp file (formatted in json) and display it as a chart on my site using Google Chart API or FusionCharts, I'm facing issues. Although I can retrieve the json data, it doesn't render as a ...

Additional directory added to the root of my website on Amazon Web Services

Out of nowhere, I've encountered an issue with my .net application on AWS Elastic Beanstalk. After redeploying, an extra segment has been added to my web root. My URL structure now appears as follows: Name.Web_deploy/default.aspx Despite not makin ...

Synchronous AJAX calls in jQuery

My system needs to handle up to 180 IO-intensive AJAX jobs on the server side, involving long running SELECT queries. To optimize CPU core usage, I want to transition from executing these AJAX calls sequentially to allowing a maximum of 4 parallel request ...

Expanding functions consist of numerous components

How can I modify this script to work on multiple elements? For example, if a user clicks on a specific link (see demo) labeled "I'd like to expand the article linked here", only that particular link should expand an element, not all like it currently ...

Tips for successfully implementing an Ocrad.js example

I've been working on an OCR (optical character recognition) web application and stumbled upon the Ocrad.js JavaScript library Ocrad.js. It seems like a perfect fit for what I need, but unfortunately, I'm having trouble getting it to function prop ...

Live text with node.js in action

Currently, my node.js server is connected to an IRC channel and I have managed to display all messages from the channel on the console. However, I am now trying to find a way to showcase these messages in real-time on a webpage. I have considered using so ...

Arrays are not being successfully passed to the controller action during an Ajax call

I have encountered an issue where I am passing an array variable to the controller. Despite the data being present in the array from the ajax call, when the controller is called it shows count=0. var url = '@Url.Action("UserRoleCompany_AddUserAcce ...

Enhancing audio control features using HTML and JavaScript

After utilizing various suggestions, I have successfully created a basic audio slider that starts playing sound (at zero volume) when clicked by the user. They can then adjust the volume as needed. My only challenge is that the volume adjustment only occu ...

Determine if a string should be matched with a regular expression if it is outside of quotation marks. If the quotation is

The desired outcomes: T1 T3 T5 T8 " = no match due to incomplete quote; potentially match characters before the quote 1a. T1 T3 T5 T8 "T4 = match T1 T3 T5, exclude T4 (optional but preferred) T1 T3 T5 T8 "T9" = match only T1 T3 T5 T8, disregard T9 O2 T ...

Making rapid formatting changes by rearranging the positioning of words in Javascript

Struggling to untangle my complex code, I'm unable to make the necessary adjustments. Here's what I have: var stocks= [ ["Beef (80/20) raw","oz",115.4451262,3.293742347,72,"4.85 gallons","5.65 pounds","0 - ",2.142,19,20,"0.0001275510204"," ...

Intercommunication between .NET 6 Web API and Blazor Server App through Callback Listener

In my current project, I have a backend .NET 6 Web API RESTful service solution that exposes a complex class. This complex class is consumed by a Blazor Server App. The challenge I am facing is ensuring that changes made to the backend Web API's insta ...

What is the best way to remove "node_modules" from my code coverage analysis?

Developing a web application in TypeScript involves using gulp with various plugins like browserify, tsify, babel, and istanbul to convert TypeScript code into JavaScript, instrument it for coverage analysis, and create sourcemaps. Testing this instrumente ...