How to send a server-side type to an ASP.NET webform to be consumed by JavaScript

Currently, I am working on passing a predefined Type (List) to an asp.net web form that needs to be recognized by JavaScript when the page loads.

The sample data I am generating appears like this:

   protected List<MapCoords> createCoordinateList()
    {
       List<MapCoords> latlng = new List<MapCoords>();
       MapCoords m = new MapCoords();
       m.xCoord = 34.241182;
       m.yCoord = -77.946839;
       latlng.Add(m);
       m.xCoord = 34.242176;
       m.yCoord = -77.94538;
       latlng.Add(m);
       return latlng
     }

I am facing a challenge in figuring out how to make this list of coordinates accessible to JavaScript on the client side. Since the object has multiple properties (x, y), setting them to a hidden field is not feasible. I have previously used ajax calls to retrieve objects, but in this case, the mock data is generated through a server-side event, eliminating the need for ajax invocation. However, I want to avoid making a redundant call if possible.

My question is, how can I transfer this list of coordinates to JavaScript on the client side while maintaining the association between x and y properties, especially considering the potential addition of more properties in the future?

Cheers,

Answer №1

If you want to pass an array of a class using a web method, you can do so in both an aspx page or a .asmx webservice. By adding the ScriptService attribute, your class array will be converted to a JSON object. Check out this example to see how it's done: jQuery Ajax with ASP.NET

[ScriptService]
public class YourClass : Page
{
    [WebMethod]   
    public static []MapCoords createCoordinateList()
    {
        //Your code
        return arrOfMapCoords;   
    }
}

Answer №2

Here's a simple example I put together for you:

Server-side code:

public class Coordinates
{
    public double latitude { get; set; }
    public double longitude { get; set; }
}
public partial class _Default : System.Web.UI.Page
{
    [WebMethod]
    public static List<Coordinates> createCoordinateList()
    {
        List<Coordinates> coords = new List<Coordinates>();
        Coordinates point = new Coordinates();
        point.latitude = 2.00;
        point.longitude = 3.1512;
        coords.Add(point);

        point = new Coordinates();
        point.latitude = 3.00;
        point.longitude = 4.1512;
        coords.Add(point);
        return coords;
    }
}

Client-side Code:

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "Default.aspx/createCoordinateList",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                if (result != null) {
                    for (i = 0; i <= result.d.length; i++) {
                        alert(result.d[i].latitude + " " + result.d[i].longitude);   
                    }
                }
            }
        });
    });
</script>

This implementation utilizes jQuery and JSON. Remember to include the jQuery library. Best of luck!

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

How to showcase numerous PDF documents within a ReactJS application

As a newcomer to the world of React, I am facing an issue with displaying multiple PDFs based on the selected link. Although I have been successful in displaying a PDF from a list of links pointing to my stored PDFs within the src directory, I encounter th ...

It appears that Promise.all is not adequately ensuring that all tasks are completed before moving on

In my current project, I am trying to achieve a complex cycle where an HTTP GET request is executed to fetch data, followed by the creation of multiple "subrequests" based on that data. The goal is to ensure that the next iteration of the cycle begins only ...

stuck with an outdated dependency causing issues with create-react-app

Encountering a problem with create-react-app failing due to react-scripts expecting an older version of a dependency, making it difficult to select the new version as suggested. This appears to be an interface issue. Interestingly, I can successfully inst ...

Calculate the time difference in hours using time zone in Javascript

Within my JavaScript object, I have the following information: var dateobj = { date: "2020-12-21 03:31:06.000000", timezone: "Africa/Abidjan", timezone_type: 3 } var date = new Date(); var options = { timeZone: dateobj.timezone }; var curr_date ...

Failed to pass through invalid parameters "recordIds", "datasources" while navigating in VUE

While working with Vue, I encountered an issue when trying to pass parameters from one route to another. Here is what my target route looks like: { path: '/record-modification', name: 'recordModification', component: recordModi ...

Unable to install vue-property-decorator

When attempting to set up Vue and TypeScript with class style using vue-property-decorator, I encountered a strange script after creating the project. I was anticipating a script like this: <script lang="ts"> import {Component, Vue} from & ...

Display array elements in a PDF document using pdfmake

Upon reaching the final page of my Angular project, I have an array filled with data retrieved from a database. How can I utilize pdfmake to import this data into a PDF file? My goal is to display a table where the first column shows interv.code and the ...

Generating links in MVC Action Methods

In my controller, I have an action method that returns a JsonResult: public JsonResult GetDetails() { var rows = //Linq-To-SQL //Linq-To-Entities var lifts = (from r in rows group r by new { r.LiftID, r ...

Challenges arising from the rendering of main.js in Vue.js

Recently, I started working with Vue and am now faced with the task of maintaining a project. Main.js contains the routing structure: Main.js import Vue from 'vue' const app = new Vue({ el: '#app', data: { message: & ...

Steps to enable the submit button in angular

Here's the code snippet: SampleComponent.html <nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)"> <label nz-radio nzValue="passed">Passed</label> <label nz-rad ...

What is the best approach to configure Nuxt.js to recognize both `/` and `/index.html` URLs?

Currently, I have set up my Nuxt.js in default mode with universal and history router configurations. After running nuxt generate, the generated website includes an index.html file in the dist folder. This means that when the website is published, it can ...

Encountering errors while running Angular 8's ng build prod command

After successfully migrating my project from Angular 7 to Angular 8, I encountered an issue when attempting to run 'ng build prod' which resulted in the following error: ERROR in Error during template compile of 'Ng2CompleterModule' Cou ...

A guide to resizing images to fit the page in React using Bootstrap

Currently, I am utilizing a function to iterate over each item in the props array and generate an image tag. My goal is to have every set of 3 images enclosed within a row div using Bootstrap to ensure proper page layout. However, I am struggling to implem ...

Are mutations in Vuex guaranteed to be atomic?

I'm currently investigating the atomicity of mutations in Vuex. The code snippet I'm reviewing has me questioning whether the CHANGE_A mutation could potentially be triggered while CHANGE_B is still in progress: const mutations = { [CHANGE_A]( ...

Vue search button not returning results

Hello, this is my HTML file. <div id="app1" v-cloak> <input v-model="term" type="search"> <button @click="search">Search</button> <p/> <div v-for="post in posts" class="post"> ...

Storing an array in $cacheFactory with AngularJS

Having some trouble saving an array in AngularJS' $cacheFactory. When attempting to retrieve the array, it's coming back as undefined. Here is the code snippet: angular.module('cacheExampleApp', []). controller('CacheContro ...

React Error: "SharedArrayBuffer is not defined" Firefox encountered a problem

I am encountering an issue with my React app that was created using 'create-react-app' along with the jsdom NPM package. Strangely, the application is throwing an error upon loading exclusively in Firefox, as it works perfectly fine in Chrome and ...

Retrieving data from radio buttons using React Hook Form

As I delve into learning React and Next.js, working with form submissions has been a breeze thanks to react-hook-form. However, I've hit a roadblock when it comes to handling radio buttons in my application. Specifically, there's a step where use ...

Awaiting the mount to the Vue event bus

I am faced with a challenge involving a Map component that initializes leaflet on the DOM in the following manner: Map.vue <template> <div ref="map"/> </template> <script> import * as L from 'leaflet'; import mapEventB ...

Implement rotation in Three.js that mirrors the functionality of Blender

Is there a way to permanently change the default rotation of a mesh in three.js after it has been loaded? For example, if I load a mesh with a rotation of 0,0,0, can I then rotate it 90 degrees on the X axis and set this new rotation as 0,0,0? It's i ...