What is the best method to retrieve the new text of a label after it has been updated on the

I'm having difficulty assigning the text of a label to a hidden field when it's not a postback. Here is the code I have written:

If Not IsPostBack Then
            Dim structPayperiod As strcPayperiodDet


            structPayperiod = objTimeSystem.getCurrentPayPeriod()
            hdnPayperiodseq.Value = structPayperiod.Payperiodid
            hdnPayPeriodStartDt.Value = structPayperiod.startdate.ToString

            lblPayPeriodStartDt.Text = structPayperiod.startdate

            displayPayrollIdOrgs(objTimeSystem.getPayrollIDOrgs())

            grd_Employees.Visible = False

            RptErrorsMessages.DataSource = objTimeSystem.getErrorMessages()
            RptErrorsMessages.DataBind()
        Else
            hdnPayPeriodStartDt.Value = lblPayPeriodStartDt.Text.ToString

        End If

The issue arises in the else clause where the value does not update with the new label value. The lblPayPeriodStartDt.Text does not seem to be updating.

The label holds a date value that updates each time I change the date using a calendar control on the client side. However, the label value does not refresh with the updated date value.

<asp:Label ID="lblPayPeriodStartDt" runat="server"></asp:Label>
<img src="../Images/calendar.gif" class="clsCursorHand" alt="" title="Select Pay Period"
                            onclick="Javascript:PayPeriodsPayroll('<%=lblPayPeriodStartDt.ClientId %>',event);"/>

Answer №1

When you make changes to an <asp:Label element on the client side in ASP.NET, it won't automatically reflect those changes on the server-side in the code behind. This is because ASP.NET labels are rendered as span elements on the client side.

Only input controls whose values have been changed on the client side are updated in viewstate. So, if you need to persist the modified value, your best option is to use a hidden field.

The workaround involves:

1. Passing the hidden field to a JavaScript function and updating its value in that function like so:

function PayPeriodsPayroll (hdnObj)
 {
   var hdnPayPeriod = document.getElementById(hdnObj);
   hdnPayPeriod.val('the value you want to set');
 }

Then, in your page load event:

If Not IsPostBack Then
   ....
Else
    // Update the label with the hidden field value if necessary
    lblPayPeriodStartDt.Text = hdnPayPeriodStartDt.Value
End If

Answer №2

It is unlikely that you are sending data back to the server every time the calendar control date is modified. One option is to trigger a postback to the server via JavaScript by utilizing the __doPostback() function. For reference, check out this resource: Javascript Postback Example

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

Trouble in Jest: Async test error

I encountered a specific error message that reads: Cannot read property 'indexOf' of undefined at Function.isPendingSpecException After some investigation, I pinpointed the problem to this particular line of code: TokenRepositor ...

Changes are being made to the Redux state without triggering any dispatch actions

I am facing an issue in my react + redux app, specifically in the editing form section. Problem Description Click on the "edit" button to modify a document The edit form is displayed Edit or delete a value within the form Instead of saving the changes ( ...

Acceptable JSON or JavaScript object for parsing

My long polling operation is functioning well when posting new objects as JSON. However, while receiving updates in the form of an object, I encountered a JavaScript object that cannot be parsed with jQuery. The issue lies in the fact that this object is n ...

Obtaining the latest state within the existing handler

In my React application, I have a handler that shuffles the state entry data: state = { data:[1,2,3,4,5] }; public handleShuffle = () => { const current = this.state.data; const shuffled = current .map((a: any) => [Math.random() ...

Ways to speed up the disappearance of error messages

There is a minor issue that I find quite annoying. The validation error message takes too long (approximately 3 seconds) to disappear after a valid input has been entered. Let me give you an example. https://i.sstatic.net/8UKrm.png Do you have any tips o ...

Encountering the error "ReferenceError: Cannot access 'data' before initialization" during deployment on Vercel

I encountered a problem with my project after trying to implement dynamic routing. Initially, everything was working fine locally and during deployment. However, when I attempted to incorporate dynamic routing, errors started to occur. Unfortunately, I am ...

Error: PDFJS is not recognized in an Asp.net environment

Trying to showcase a PDF using the canvas and PDF.JS Stable v.2.2.228, but encountering an error in the console that says: ReferenceError: PDFJS is not defined. Information points towards the removal of the global PDFJS object; however, struggling to find ...

When you click on a sublevel in the vertical CSS and JavaScript onclick menu, it disappears automatically

I'm a beginner when it comes to Javascript, and I'm still getting the hang of CSS/HTML. Currently, I am working on creating a vertical menu using CSS and javascript. My goal is to have the sublevels appear on the right side of the menu when someo ...

Issue with adding a new record in detailsview while in insert mode

I have implemented a detailsview that is always in insert mode. Users will only be creating new records, and not editing or viewing existing ones. However, I am facing an issue where clicking the insert button after filling out all fields does not add a ne ...

Adjust the height of the image slider to match the smallest image

Currently, my responsive image slider is using . The height of the slider is being set to match the height of the largest image. However, I would like it to instead be the height of the smallest image and cut off any excess for images that are larger than ...

Having difficulty in uploading a batch of 5 pictures simultaneously using the formData array

Struggling to upload 5 pictures at once? You're not alone. Even though uploading 4 works just fine, the fifth one seems to be causing trouble. Take a look at my code below and see if you can spot where I've gone wrong. Any help would be greatly a ...

What is the best way to include multiple action creators in a single listenerMiddleware in Redux Toolkit?

I am looking to store the current state in my database every time there is a change in any of its properties. I have implemented two middlewares to handle this task, each responsible for dispatching the saveTrip function. Although both middlewares are ide ...

What is the rationale behind axios adding the current URL to API requests in Laravel or React?

I am currently working on a project that involves Laravel, React, and Redux. The following code snippet is from a function called by a Redux Saga worker: function fetchItems() { return axios.get('/api/items').then(response => response.dat ...

Unable to retrieve the /socket.io/socket.io.js file in the client-side application

My server side application is currently hosted on heroku: The code snippet that is relevant to this issue is as follows: const express = require('express'), app = express(), server = require('http').createServer(app), ...

Encountered a 'SyntaxError: await is only valid in async function' error while trying to utilize the top-level await feature in Node v14.14.0

I'm excited to use the new top-level await feature that was introduced in Node version 14.8. For more information, you can check out this link and here. I did a thorough search but couldn't find any questions related to issues with the new featur ...

Preventing event propagation in Angular when clicking

What is the best way to call an Angular function within my jQuery code? I attempted to do so with the following: $(document).on('click', '.myBtn', function(e) { angular.element($(".someClass")).scope().clearBtnItems(); e.stop ...

Verify if the items in the array are based on ASCII codes

I'm looking to extract ASCII codes from elements within an array. Here's a sample array: var elem = ["Joe", "M"+String.fromCharCode(13)+"ry", "Element_03", "Element_04"]; I tried using a for loop to scan through the array and check for ASCII co ...

Stop the form from refreshing the page after submitting a post request to the backend API

I am facing an issue with my React front end and Express back end integration. I have a form in my front end that sends data to the API using two buttons - Submit and Close. The Close button works perfectly by closing the overlay without leaving the page, ...

Troubleshooting Tips for Resolving Problems with VueJS getElementById Bug

I'm currently working with a VueJS single File component that has the following template: <template> <div class="row"> <div class="col-md-12"> <div id="hottable"></div> < ...

Apply a different background color to ion-item when it is clicked

Is there a way to change the background color of an ion-item when it is clicked by a user? Any help on how to achieve this would be greatly appreciated. Here's an example code snippet: <ion-item (click)="openDetail(variant)">{{variant.Product ...