Retrieve the innerHtml value of an asp.net Label using C# programmatically

I have a JavaScript function that successfully retrieves the cursor position value. I am assigning this value to an ASP.NET label's innerHTML property. How can I access this innerHTML property when a treeview_selectednodechange event occurs in my program?

This is the JavaScript function I am using:

function ShowSelection() {
        var txt1 = document.getElementById("MainContent_txtQuery");
        var currentRange = document.selection.createRange();
        var workRange = currentRange.duplicate();
        txt1.select();
        var allRange = document.selection.createRange();
        var len = 0;
        while (workRange.compareEndPoints("StartToStart", allRange) > 0) 
        {
            workRange.moveStart("character", -1);
            len++;
        }
        currentRange.select();
        document.getElementById("MainContent_lblPos").innerHTML = len;
    }

The section where I need to access it is:

 string[] selectedNode = treeViewTables.SelectedNode.Text.Split('<', '>');

            string pos = lblPos.Text;
            if (selectedNode[2].Equals("Table(s)") || selectedNode[2].Equals("Parameter(s)"))
            {
                return;
            }
            string parentNode = treeViewTables.SelectedNode.Parent.Text;

            if (parentNode.Contains("Table(s)"))
            {
                txtQuery.Text = txtQuery.Text + " " + selectedNode[2];
                txtQuery.Text = RemoveSpaces(txtQuery.Text);
            }
            else if (parentNode.Contains("Parameter"))
            {
                //if (txtQuery.Text != "")
                if (lblPos.Text == string.Empty)
                {
                    if (txtQuery.Text.Length == 0)
                    {
                        txtQuery.Text = selectedNode[2];
                    }
                    else if (txtQuery.Text[txtQuery.Text.Length - 1] != ',')
                    {
                        txtQuery.Text = txtQuery.Text + " " + "'" + selectedNode[2] + "'";
                        txtQuery.Text = RemoveSpaces(txtQuery.Text);
                    }
                    else
                    {
                        txtQuery.Text = txtQuery.Text + " " + selectedNode[2];
                        txtQuery.Text = RemoveSpaces(txtQuery.Text);
                    }
                }

            }
            else
            {
                txtQuery.Text = txtQuery.Text + " " + selectedNode[2] + ",";
                txtQuery.Text = RemoveSpaces(txtQuery.Text);
            }
            TreeNode nodeSelected = treeViewTables.Nodes[0];
            nodeSelected.Select();

Any assistance would be highly appreciated.

Thank You

Answer №1

A label's content (represented by a span on the client side) will not be sent back to the server.

To ensure that the value is accessible on the server side, include an <asp:HiddenField>. Set its value on the client side simultaneous with updating the innerHtml of the label.

Answer №2

Elements within the DOM do not travel back and forth to the server, only form elements have that capability. The information accessible on the server from a Label is limited to what was initially configured on the server side.

If you wish to achieve your desired outcome, you will need to generate a Hidden field and assign your coordinate values to it. This way, the information will successfully reach the server during postback.

Answer №3

It seems like you are attempting to modify the content of a label control using javascript and then retrieve it on the server side in ASP.NET with C#, is that correct?

If that is your goal, unfortunately, you won't be able to achieve it because a label control is actually rendered as an HTML span element, not a form element. Only form elements are sent back to the server during postback (either full or partial). One alternative could be setting the same value to a hidden field and accessing it on the server side, or utilizing an AJAX call to send it back to the server.

In addition, it's generally not recommended to directly reference rendered Client IDs in javascript code. So instead of

document.getElementById("MainContent_txtQuery")

it would be safer to use

document.getElementById("<%=txtQuery.ClientID%>")

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

Ways to modify the default text in a dropdown menu?

I'm currently attempting to modify the title of a dropdown using the Multi-select plugin found here. However, I've encountered an issue where I am unable to dynamically change the text (Dropdown title) of the dropdown using JavaScript. $(' ...

The @Html.Label feature fails to appear when the content includes a period (.) - Utilizing Bootstrap with MVC Razor

I am dynamically populating label text from a database source <div class="col-11 col-sm-11 col-md-11 col-lg-11 col-xl-11"> @Html.Label(@Model.Questions[i].DataText + ": ", new { @for = "dd" + @Model.Questions[i].Data ...

Using the v-for directive to create sequential lists

I am struggling to display pairs of data from an object based on category using nested v-for loops. The object, categoryArray, contains entries such as {stage 1, red}, {stage 1, blue}, {stage 2, orange}, {stage 3, brown}, {stage 2, green. My desired displ ...

swapping the final word in a string with Node.js or JavaScript

var str = "Demo Docs Version 1.0.1"; var gotWord = str.split(" ").splice(-1)[0] str = str.replace(gotWord, "testing"); console.log(str); If there is a space between words, I can replace the last word. But how do I replace the last word when ...

What is the best way to remove a dynamically created control from an UpdatePanel when a button is clicked?

I'm experiencing an issue with my ASP.NET UpdatePanel where I dynamically add smaller panels that have their own "Delete" button. The problem arises when I click on the "Delete" button - nothing happens initially, but then after another operation tri ...

remove unnecessary parameters from a JavaScript object using curly braces

My query pertains to an object response below result.joblist = { "collection_job_status_list": [ { "application_context": { "application_id": "a4", "context_id": "c4" }, "creation_time": "15699018476102", "pro ...

Issue with reading initial state value in React application

I'm currently working on an application centered around payment recording functionality. Within my app, there is a state structure that looks something like this: const [state, setstate] = useState({ amountPaid: Number(bill.total), // the 'b ...

Performing a Javascript query to update the value in a spreadsheet with Selenium integration

How can I set a cell value using JavaScript in Selenium when the element has been created using spreadjs and I am unable to access the element's value? string query = "GcSpread.Sheets.findControl(document.getElementById(\"" + _sheetName + "&bsol ...

What are some strategies for sorting information from a list that is constantly changing?

I have been working on a web application built in asp.net that receives data from a web service in JSON format. The current task is to dynamically develop controls for this application. I achieved this by creating a list of labels with stored values using ...

A step-by-step guide on how to use ajax/jquery to access an external webpage without relying on iframe

Is there a more effective way to call another page, such as http://www.google.com, and load it into my specific div without using an iframe? I attempted to do so with ajax... $.ajax({ url : 'http://www.google.com', success : function ( ...

The inclusion of react-helmet in my Gatsby website is leading to an issue where the element type is considered invalid

Incorporating the Layout component in my app has significantly improved the styling. This is where I introduced react-helmet. This is how the component looks: import React from 'react'; import { Global, css } from '@emotion/core'; im ...

Error: The SpringBoot API returned a SyntaxError because an unexpected token < was found at the beginning of the JSON response

I am currently following a tutorial on Spring Boot React CRUD operations which can be found here. However, I have encountered an issue when trying to fetch JSON data from the REST API and display it in my project. Despite following the steps outlined in th ...

Can you update the `runtime` property to `segment` in the export config?

I'm currently working on setting up an upload API route within my application. /admin/upload However, when I attempt to console.log(req.file), it returns as undefined. This seems to be related to the following configuration: export const config = { ...

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 ...

Retrieving data from Firebase query and displaying as an array of results

Currently utilizing the @react-native-firebase wrapper for interaction with Firebase's Firestore. Within my function, some querying to a specific collection is performed, with the expected result being an Array object containing each located document. ...

What causes z-index to be ineffective with sticky elements?

In my website, I've implemented rollover effects in a sticky footer and a responsive menu that stays at the top. However, when the menu is opened and extends over the footer, it covers everything except the rollovers. Closed navigation http://www.mus ...

The bootstrap switch button remains in a neutral grey color

Ordinary: Initially clicked: Click again: After the second click, it remains grey and only reverts on a different action like mouse click or selection. Is there a way to make it go back to its original state when unselected? ...

Tips for cutting down on bundle size in your WEBPACK setup when using VUEJS

I have tried numerous tutorials to reduce the size of my bundle, but none of them seem to be affecting the bundle size and I can't figure out why. Every time I integrate new code into webpack, the bundle size remains unchanged. (The application is c ...

Adjust the CSS property of a div to have a fixed position when scrolling

I attempted to implement a fixed div on scroll in Vue.js using the following code: ... async created() { window.addEventListener('scroll', this.calendarScroll); } methods: { calendarScroll() { console.log('Scroll'); cons ...

Conflict in the naming and scoping of IE7 and IE8

While reviewing some code, I encountered a problem in Internet Explorer 7 and 8. Despite the constructor executing properly when stepped through, upon returning I received an error stating "Object does not support this property or method." How frustrating! ...