Retrieving the text or value of an ASP.NET label using JavaScript

One of my challenges is transferring a string of data from C# to JavaScript in ASP web forms. My plan involves setting the data as a text for an ASP label in C#, then extracting the label's text by ID in JS.

This is the C# code (ascx.cs file):

    List<Event> eventList;

    protected void Page_Load(object sender, EventArgs e)
    {
        string message = string.Empty;
        SPSite franasabank = new SPSite("http://lbshrptweb/sites/fransabank/");
        SPWeb calendar = franasabank.OpenWeb();
        SPList list = calendar.Lists["Fransabank Calendar"];
        eventList = new List<Event>();
        foreach (SPListItem oItem in list.Items)
        {
            // Access each item in the list...  
            DateTime startTime = (DateTime)oItem["Start Time"];
            DateTime endTime = (DateTime)oItem["End Time"];
            string status = (String)oItem["Status"];
            string title = oItem.Title;
            string description = (String)oItem["Description"];
            Event calendar_event = new Event(startTime, endTime, status, title, description);
            eventList.Add(calendar_event);
        }
        foreach (Event item in eventList)
        {
            message += item.Title + " " + item.Description + item.StartDate + "-" + item.EndDate + "-" + item.Status + "\n";
        }

        Label1.Text = message;
    }

This snippet shows the HTML with the Label (ascx file):

<div data-ng-app="Calendar">
   <div data-ng-controller="CalendarController" id="mycontroller">
     <div class="row " data-ng-init="Initialize()">
        <asp:Label ID="Label1" runat="server" Text="Label" ></asp:Label>

And here is the JavaScript code:

<script>
    var a = document.getElementById('<%= Label1.ClientID %>');
    console.log(a);
</script>

Despite this setup, I'm finding that the data comes through as null in variable 'a'. I've attempted:

var a = document.getElementById('<%= Label1.ClientID %>').innerHTML;

But unfortunately, it also results in null values.

Answer №1

It appears that Javascript is executing before the label has fully loaded

  1. Move the js code after the <asp:Label> on the page, ideally right before </body>:

        <script>
            var a = document.getElementById('<%= Label1.ClientID %>');
            console.log(a);
        </script>
    </body>
    
  2. Another option is to wrap the code block with jQuery's $(document).ready():

    <script>
        $(document).ready(function () {
            var a = document.getElementById('<%= Label1.ClientID %>');
            console.log(a);
        });
    </script>
    

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

Guide: How to include a date value within a JSON format? [See code snippet below]

Currently, I am developing a react application that includes a form with sections for basic details and employment information. The form is almost completed, and I have successfully structured the data in JSON format for different sections. To see a work ...

What is the best way to limit a plugin to only one version of jQuery when there are 2 versions included on a page?

As I develop a piece of Javascript code to embed into my client's websites, I have concerns about potential conflicts with other versions of jQuery that they may be using. While I have found some guidance in the jQuery documentation, implementing it l ...

Unable to interpret data from the API

{ id: 8, customerName: "xyz", customerMobileNumber: "123456789", customerBillingAddress: "xyz address", customerShippingAddress: "xyz address", customerProductPurchasedDate: "2021-11-09T09:07:00.000Z", cust ...

Troubleshooting issues with sending POST requests in node.js

I've been attempting to initiate a post request, but for some reason, it's not going through. Strangely, I'm not seeing any output in the console log of my browser. My node server.js is up and running on x.x.x.x:8000. I've connected it ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

What is the process of extracting a value from an array of objects based on another parameter?

Given the array below which contains objects with nested arrays, my goal is to retrieve the value 'AUS Eastern Standard Time' when 'Australia/Melbourne' is passed to the array. Although I attempted to use the code var winTimeZone = arr ...

AngularJS, building a hash of resources

Is there a way, in an AngularJS controller, to take a URL and redirect that request to the best place for fetching JSON data? The VideoSearchCtrl is connected to the search form. Everything seems fine with the generated URL for the template, so I aim to us ...

Are you familiar with the Puppeteer PDF tool that generates empty pages from the cloud and seamlessly integrates with Postman? What do

After days of searching, tweaking, and deploying, I still can't get this to work. I'm hoping it's just a simple mistake on my part that someone else can help me with. I am attempting to use Puppeteer to generate a PDF from a Node.js Express ...

Traversing an object with a loop

I'm currently working on a project that involves utilizing the swapi co API. Although I've successfully fetched results from the website, I'm struggling with displaying only specific API objects, particularly array spaceships. var linkApi=" ...

Having trouble updating the value of my textfield in material-ui using formik

Below is the code I'm working with to set a default value using the material-ui Textfield API within a formik fieldarray: <TextField name={`myGroups.${index}.myGroupName`} value={`Group ${index+1}`} label="Group" InputProps={{ ...

I am looking to set an HTML file as the homepage for my Next.js project

Is there a way in next.js to render a normal .html file (index.html) when someone visits my root directory at "https://example.com/"? I have researched and edited my config file as shown below, /** @type {import('next').NextConfig} */ const next ...

What is the proper way to direct to a webpage in a different directory?

I have a simple question that is causing me some confusion: In my solution, I have Folders A & Folder B FolderA contains aspx pages 1 & 2 FolderB contains aspx pages 3 & 4 From Page 2, I need to open page 4 I attempted to use the follo ...

What is the process for inputting client-side data using a web service in ASP.NET?

Currently experimenting with this: This is my JavaScript code snippet: function insertVisitor() { var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>' $.ajax({ type: "POST", url: pageUrl + "/inse ...

What is the best way to obtain the chosen value or index from a Vue select element?

On the surface, this question seems straightforward, but there are some complexities to consider. The scenario involves: <select id="lstMash" @change="onChange()"><option value="valid">Valid</option><option value="warning">Warning& ...

What is the best way to empty an input field after adding an item to an array?

In my Angular 2 example, I have created a simple functionality where users can add items to an array. When the user types something and clicks the button, the input is added to the array and displayed in a list. I am currently encountering two issues: 1 ...

Error: Failed to retrieve the name property of an undefined value within the Array.forEach method

Upon pressing the button to display the task pane, I encountered an error message in the console window that reads: "Uncaught (in promise) TypeError: Cannot read property 'name' of undefined". This error persists and I am unable to resolve or com ...

What is the best way to terminate a "for await ...of" loop if it fails to finish within a specified timeframe?

Is it possible to stop an asynchronous loop if it doesn't finish within a set time frame? I'm working with the following code: (async()=>{ for await(let t of asynDataStreamOrGenerator){ //some data processing } //some other code I n ...

Enhance user experience with real-time form validation in Bootstrap 4 as the user inputs

In order to troubleshoot my issue, I created a simple index.php file with 2 input fields and a button that redirects to page2.php. These input tags have a regex pattern for Bootstrap-4 form validation. Issue 1: The validation only occurs after clicking ...

Tips for creating emissiveMap lighting exclusively in dimly lit spaces using three.js

Using three.js, I am able to render the earth with textures and add an emissive texture for city lights. However, I am facing a problem where even the light areas of the earth emit city lights. For example: https://i.sstatic.net/hZ1Cr.png Is there a way ...

What is the significance of the source element in Vue3's audio element?

Playing mp3 files works in Vue 2, but not in Vue3. <template> <audio src="../file_example_MP3_700KB.mp3" controls ></audio> </template> In Vue3, the code needs to be modified as follows: <template> <audi ...