ClientScript call fails to store values in controls of a web page

I encountered an issue with preserving the value of a TextBox when the page is refreshed using F5. It seems that if I include the // Loading(); function call in the Page_Load(), the TextBox retains its old value. However, as soon as I remove this comment, the value is lost in TextBox1.

I'm seeking to understand the reason behind this behavior and what steps can be taken to prevent it.

    <script type="text/javascript>

      function TextBox1_TextChanged() {
       <%
           Session["HitCount1"] = TextBox1.Text ;
       %>

     }

     function getMyvalSession() {
            var ff = "Loading Value";
           return ff;
     }

    </script>

<body>
    <form id="form1" runat="server">

    <asp:TextBox ID="TextBox1"  Name="TextBox1"  runat="server" 
 AutoPostBack='true'  onchange="TextBox1_TextChanged()"></asp:TextBox>

          <%
                 string x = null;
                  x = Session["HitCount1"].ToString().Trim();

                  if ((x.Equals(null)) || (x.Equals("")))
                 { 
                     // Session Variable is either empty or null .
                 } 
                 else 
                 {
                     TextBox1.Text = Session["HitCount1"].ToString();
                 }
          %>

  </form>
</body>

    protected void Page_Load(object sender, EventArgs e)
    {
      //  Loading();
    }

    void Loading()
    {
        String csname = "OnSubmitScript";
        Type cstype = this.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = Page.ClientScript;

        // Check to see if the OnSubmit statement is already registered.
        if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
        {
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession()  ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
        }


    }

Answer №1

It's generally not advisable to mix inline server-side code with code-behind code. My suggestion would be to stick to using only the code-behind code for better results.

Take a look at this piece of code:

  function TextBox1_TextChanged() {
   <%
       Session["HitCount1"] = TextBox1.Text ;
   %>

 }

... this code won't achieve the desired outcome of setting the (server-side) Session entry "HitCount1" to the value of Textbox1.Text. This is because TextBox1_TextChanged is a client-side function and the assignment statement is for the server side. At runtime, the server code chunk will be removed by the compiler, leaving TextBox1_TextChanged as an empty function.

Remember: actions occur on the client side, on the server during postback, or on the server through Ajax calls. Mixing client and server code is not recommended.

My advice: transition to utilizing code-behind for all tasks. Once everything is functioning correctly, consider incorporating Ajax calls if there are too many postbacks.

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

identify when the React component has reached the bottom of the element by reading the

Is there a way to access the scroll handler's event without being able to access offsetTop, scrollTop, etc? class App extends React.Component { handleScroll = e => { console.log(e.target.scrollTop); }; componentDidMo ...

Tips for receiving a reply from a post request

After successfully making and completing a post request, I'm wondering about using console.log(res.valor) in the code to display the data: consultarCorreio(){ this.cartS.cart.valorTotalItems this.cartS.getCorreiosPrazoPreco(this.cartS.cart.pesoTot ...

Searching for values within an array using the ".includes" method

I'm curious if there's a method to determine if a string contains any characters that are also present in an array? const array = ["cake", "hello", "ok"]; const string = "hello"; let result = string.include ...

Change the color of the menu icon based on the specified HTML class or attribute

I'm trying to create a fixed menu that changes color depending on the background of different sections. Currently, I am using a data-color attribute but I am struggling with removing and adding the class to #open-button. Adding the class works fine, ...

Node.js command prompt claims that 'react is non-existent'

Hello everyone! I'm excited to ask my first question on this site. I am relatively new to coding and currently learning React. Yesterday, I started working on my first project. Today, when I tried to initialize live-server and babel compiler for my J ...

Using the Angular translate filter within a ternary operator

I am currently working on translating my project into a different language. To do this, I have implemented the Angular Translate library and uploaded an external JSON file containing all the translations. Here is an example of how it looks: { "hello_wor ...

Why won't my AngularJS Google Maps marker trigger any events?

My issue is with the marker event not working on a UI Google Map. I am using this link. Here is my view setup: <ui-gmap-markers models="mapResult" fit="true" idkey="mapResult.id" coords="'form_geo'" click="'onclick'" events="mapRe ...

Deciphering decimal numbers from a text

Is there a way to extract the floating point numbers from an array like this: var array = "-51.2132,0.3100"; I attempted to use match(/\d+/g) but I'm looking to specifically extract floating point numbers Any suggestions on the appropriate reg ...

An array filled with unique and non-repeating elements

I want to display random country flags next to each other, making sure they do not match. However, my specific case requires a unique solution for dealing with arrays: function displayRandomFlags() { var flagurls = ["ZPlo8tpmp/chi","cJBo8tpk6/sov","QyLo ...

Steps for designing a movable image

I'm looking to implement a feature where the user can drag and drop an image anywhere on the page. Once the user places the image, its position will be saved so that when they revisit the page, it will be in the same location. Thank you! ...

Execute the cucumber tests based on tags or run all the tests

I am facing challenges when it comes to running cucumber tests. I aim to execute either all scenarios if tags are not provided as a CLI argument, or specific scenarios based on the passed tags as CLI arguments. Here is my configuration file: module.exports ...

Getting the selected item from a dropdown menu and including it in an email

While working in React, I have successfully created a contact form that includes fields for name, email, and a message box. When the form is submitted, these three items are sent as expected. However, I am facing difficulty in sending a selected item from ...

Inquiry from a newcomer: ASP.NET with jQuery

I am working on a webform with a file upload button that has some specific requirements. Whenever the file is uploaded using the button, I need the C# code behind to execute first before any jquery functions are called. <script> $(document.read ...

Identify when the Vue page changes and execute the appropriate function

Issue with Map Focus Within my application, there are two main tabs - Home and Map. The map functionality is implemented using OpenLayers. When navigating from the Home tab to the Map tab, a specific feature on the map should be focused on. However, if th ...

Utilize JavaScript variables with jQuery: A simple guide

I need assistance with adding a class after selecting the checkbox. The variable values come from a database using PHP. var a = user<?php echo $i; ?>; Although this displays the correct value, I am struggling to pass it to jQuery in order to add the ...

Adjust color scheme of drop-down menu

Having trouble changing the background color for my drop down menu. I tried to change the color for the sub div but it's not working. Can anyone help me fix this issue? Here is the code snippet: http://jsfiddle.net/3VBQ6/4/ #nav li:hover ul.sub li { ...

Sending a string parameter from an AJAX function to a Spring controller

I'm currently developing a standalone application and facing an issue with passing a string, which is generated from the change event, to the spring controller using the provided code snippet. Here is the HTML CODE snippet: <!DOCTYPE HTML> < ...

Updating variable storage in React components

This is a project built with Next.js and React. Below is the folder structure: components > Navbar.js pages > index.js (/ route)(includes Navbar) > submitCollection.js (/submitCollection)(includes Navbar) The goal is to allow users to inpu ...

What is the best method for placing an element above all other elements on a page, regardless of the layout or styles being used?

I want to create a sticky button that remains fixed on the page regardless of its content and styles. The button should always be displayed on top of other elements, without relying on specific z-index values or pre-existing structures. This solution must ...

This error occurs when trying to assign a value to a property of a variable that is currently undefined

Having some issues with assigning the latitude and longitude values to a variable in my code. I am able to retrieve them correctly, but when trying to use them in another method (onUpload()), I am facing some errors. export class latlonComponent implement ...