How can I access a list in the code behind of an ASPX file and iterate through it using JavaScript in a foreach

Here is the code snippet in my aspx.cs file:

public partial class BarChart 
{
    public class LabelsDetail
    {
        public string LabelId { get;set; }
        public string LabelDesc { get; set; }
    }
    public List<LabelsDetail> LabelsDetails { get; set; }

    public void InsertDataToLabelsDetails()
    {
        // Data is populated into "LabelsDetails" from a source

    }

}

Along with the following JavaScript code on the ASPX page:

function setupBarChart(JQObjectContainer, JsonData) {
    var hashTableSize = <%=this.LabelsDetails.Count%>;
    var hashtable = {};

    if (hashTableSize != 'undefined' && hashTableSize > 0)
    {
        for (var item in <%=this.LabelsDetails%>)
        { 
            hashtable[item.LabelId] = item.LabelDesc;
        }
    }

}

I am trying to iterate over a server-side list in the client-side. How can I achieve this?

Currently, when attempting to loop through the server-side list (this.LabelsDetails), I encounter an error

Uncaught SyntaxError: Unterminated template literal
.

Any guidance or assistance would be greatly appreciated.

Answer №1

Give this a shot

function configureBarChart(container, data) {
            var size = <%=this.LabelsDetails.Count%>;
            var hashTable = {};
            var jsonData = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(this.LabelsDetails)%>;
            if (size != 'undefined' && size > 0)
            {
                for (var item in jsonData)
                { 
                    hashTable[jsonData[item].LabelId] = jsonData[item].LabelDesc;
                }

            }
}

Answer №2

To ensure JavaScript can understand your collection, you need to convert it into a compatible notation. One way to do this is by utilizing the JavaScriptSerializer or any JSON converter:

var collection = new[]{
    new { Name = "a" },
    new { Name = "b" },
    new { Name = "c" },
    new { Name = "d" }
};

System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();

Console.WriteLine(s.Serialize(collection));

The output will be

[{"Name":"a"},{"Name":"b"},{"Name":"c"},{"Name":"d"}]
, which is a valid array format for JavaScript. When iterating in JS, consider optimizing your approach:

var array = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(this.LabelsDetails)%>;
for(var x=0;x<array.length;x++)
{ 
    hashtable[array[x].LabelId] = array[x].LabelDesc;
}

It's important to note that using For...In loop to iterate arrays in JS differs from C#'s foreach. According to MDN:

Array iteration and for...in

Note: for..in should not be used to iterate over an Array where the index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

Consider exploring alternative technologies to enhance the connection between client-side and server-side operations.

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

The $.get route is failing to execute on the server-side, resulting in no data being retrieved. The server is not logging any information about this

I'm facing an issue where the $.get method is no longer working for me. I have simplified my code as much as possible, but it still doesn't work. Here is the code snippet: $("#test").click(function() { console.log("I'm in the on click e ...

transferring information from browser storage to the server

On my web app, there is a feature that saves data to local storage and converts it to a JSON object. I'm interested in passing this local storage data to my server using AJAX, so that other clients of the web app can access it. Is there a way to accom ...

A guide on dynamically filling a dropdown menu based on the selection made in another dropdown using PHP and JSON data

Looking to create a dynamic select box based on another select box <select> <option value="x">x</option> <option value="y">y</option> </select> <select> <option value="1">1</option> ...

Issue when attempting to update the state using the spread operator

I'm currently developing a react application and I've encountered an issue. My goal is to update the state object within my reducer using parameters supplied by the action creator. To simplify, I've created an example in pure JS Here is how ...

Ways to perform a jQuery selection beginning with a pre-existing jQuery object

When working with Vanilla JavaScript, you can select an element from the DOM using the following method: let element = document.querySelector('[css selector]'); Once you have the element selected, you can further target elements within it using ...

Troubleshooting: AngularJS - Issues with nested controllers not functioning properly within ng-include

According to the AngularJS documentation (refer to nested controller fragment), I am attempting to implement nested controllers using ng-include Main.html <body id="spaWrapperApp" ng-app="spaWrapperApp"> <div class="container-fluid" id=" ...

employing JavaScript code for targeting classes rather than IDs

I am facing an issue with a javascript function called MyFunc() that is currently only working with id="item_for_MyFunc". Within the function, there is a var elem = document.getElementById("item_for_MyFunc"); and the HTML body contains: <body onload= ...

Exploring deeper into accessing nested properties with Handlebars

I am attempting to utilize handlebars for displaying a list obtained from a complex JSON. The data structure is challenging to navigate, preventing me from accessing the nested property I require. The data structure is as follows: var data = [{ " ...

Creating an array of objects in Javascript by setting two different values as a range

Given an array of objects structured as follows: [{value: "a", start: 1950, end: 1954, description: "aaa"}, {value: "b", start: 1953, end: 1956, description: "bbb"}, {value: "c", start: 1960, end: 1962, des ...

Exploring the benefits of utilizing express-session for authentication management

I am currently in the process of creating a basic login application using express 4 and express-session. When setting up my code as follows: app.use(session({ store: new MongoStore({ db: 'sess' }), secret: 'Ninja Turtle', cookie ...

Unwrapping React: Mastering the Art of Prop Extraction and Sharing

Imagine I have 2 input elements below, both with the same props except for the className <ReactCardFlip> <input type="text" maxLength={1} className={inputStyles.input} defaultValue={value} ...

Tips for updating only the modified fields in the .NET entity framework when utilizing stored procedures for performing insert, update, and delete operations

After utilizing the .NET Entity Framework to map my database tables and implementing stored procedures for insert, update, and delete operations, I integrated EntityDataSource into my ASP.NET application for updating a specific table. Even though I do not ...

Unable to send a namespaced action from a different module: [vuex] action type is not recognized

In my coding project, I am working with two different modules called activities and alerts. One of the requirements is that whenever an activity is added, I need to trigger an alert action with the namespaced identifier alerts/SHOW. This functionality was ...

What is the best way to create a drop-down menu that exports data directly to an Excel spreadsheet?

I have been struggling with a seemingly simple issue - I can't seem to get my drop-down box to display the chosen option. The code I'm using is quite similar to this generic one, but for some reason, it's not reporting the selected option to ...

Issues with VueJS rendering have been observed on MacOS with both Safari and Chrome browsers

Encountering an unusual issue here. My VueJS application, sourced from CDN, incorporates Vuetify. Interestingly, it functions seamlessly on Ubuntu and Windows; however, my client reports observing raw VueJS code when accessing the app via Safari on his iP ...

Is it possible to change a CSS variable using VueJS?

With CSS Modules, we are able to utilize variables in both our CSS and JS code. // Using it in template ... ...<p :class="{ [$style.red]: isRed }">Am I red?</p> // Using it in JS ... ... <script> export default { created ( ...

MergeTransformer: Stylish Bundle

Currently, I am utilizing the wonderful BundleTransformer Nuget package to dynamically compile SCSS through the ASP.NET bundling and minification pipeline. I am in the process of integrating the bootstrap.sass package into my project, but I keep encounteri ...

Finding out the nature of nullable attributes within an object: How can it be done?

I'm facing an issue with saving incomplete forms where I have a form being filled out by a user and I wish to allow the form to be saved even if it's not fully complete. Before sending the object to my API, I need to set any null attributes to e ...

I am unable to place a new grid on a new line

As a novice, I am attempting to construct a page that showcases a collection of cards. Although I have designed the header of the page in my own unique way, I am encountering issues when trying to display the cards within a new Grid container. The initial ...

Using axios with async/await to handle unresolved promises in Javascript

I'm facing a challenge with a piece of code I've been working on. Despite my efforts to find a solution online, I haven't had any success so far. Here is the code snippet in question: const fetchSidebarData = async () => { let da ...